<template>
  <div class="filter-view">
    <!-- 顶部标题栏 -->
    <div class="header">
      <div class="title-bar">
        <button class="title-button" @click="handleIndicatorClick">📊 指标</button>
        <h1>股票筛选</h1>
        <span class="filter-link" @click="toggleFilterPanel">🔍 筛选</span>
      </div>
    </div>

    <!-- 列选择器对话框 -->
    <div class="column-selector-dialog" v-if="showColumnSelectorDialog">
      <div class="dialog-overlay" @click="handleCloseColumnSelector"></div>
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>自定义列顺序</h3>
          <button class="close-btn" @click="handleCloseColumnSelector">&times;</button>
        </div>
        <div class="dialog-body">
          <div class="selector-columns">
            <!-- 已选列 -->
            <div class="selected-columns">
              <h4>已选择的列</h4>
              <div class="column-list">
                <div v-for="(column, index) in selectedColumns" :key="column.key" class="column-item">
                  <span>{{ column.label }}</span>
                  <button @click="removeColumn(index)" :disabled="selectedColumns.length <= 1">移出</button>
                </div>
              </div>
            </div>

            <!-- 未选列 -->
            <div class="available-columns">
              <h4>可选列</h4>
              <div class="column-list">
                <div v-for="column in availableColumns" :key="column.key" class="column-item">
                  <span>{{ column.label }}</span>
                  <button @click="addColumn(column)">移入</button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="handleCloseColumnSelector">取消</button>
          <button class="btn btn-primary" @click="handleCloseColumnSelector">确定</button>
        </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="content">
      <!-- 表格容器 -->
      <div class="table-container">
        <!-- 表格头部 -->
        <div class="table-header">
          <div v-for="header in renderTableHeader()" :key="header.column" class="header-cell" :class="{ 'sortable blue-text': header.sortable }" @click="header.sortable ? handleSort(header.column) : null">
            <span>{{ header.name }}</span>
            <span v-if="header.column === 'pct_chg'" class="time-range">2M-9M</span>
            <span v-if="sortField === header.column" class="sort-icon">
              {{ sortOrder === 'asc' ? '↑' : '↓' }}
            </span>
          </div>
        </div>

        <!-- 表格内容 -->
        <div class="table-body">
          <!-- 平均值/中位数行 -->
          <div class="table-row average-row">
            <div v-for="(cell, index) in renderTableRow(currentSummary)" :key="index" class="table-cell" :class="{ 'summary-toggle': index === 0 }" @click="index === 0 ? toggleSummaryType() : null">
              <template v-if="index === 0">
                {{ summaryType === 'average' ? '平均值' : '中位数' }}
                <span class="toggle-icon">{{ summaryType === 'average' ? '↓' : '↑' }}</span>
              </template>
              <template v-else>
                {{ cell.value }}
              </template>
            </div>
          </div>

          <!-- 动态数据行 -->
        <!-- 渲染详细数据 -->
        <div v-for="(stock, index) in stocks" :key="stock.symbol + '_' + index" class="table-row">
          <div v-for="(cell, cellIndex) in renderTableRow(stock)" :key="cellIndex" class="table-cell" :class="cell.className">
            <template v-if="cellIndex === 0">
              <div class="stock-name" v-tooltip="stock.name">{{ stock.name }}</div>
              <div class="stock-code" v-tooltip="stock.symbol">{{ stock.symbol }}</div>
            </template>
            <template v-else>
              {{ cell.value }}
            </template>
          </div>
        </div>
        </div>

        <!-- 分页控件 -->
        <div class="pagination">
          <div class="pagination-info">
            共 {{ totalItems }} 条记录，每页显示
            <select v-model="form.page_size" @change="onPageSizeChange">
              <option value="20">20</option>
              <option value="50">50</option>
              <option value="100">100</option>
              <option value="200">200</option>
              <option value="500">500</option>
              <option value="950">950</option>
            </select>
            条
          </div>
          <div class="pagination-controls">
            <button @click="changePage(1)" :disabled="form.page === 1">首页</button>
            <button @click="changePage(form.page - 1)" :disabled="form.page === 1">上一页</button>
            <span class="page-info">第 {{ form.page }} / {{ totalPages }} 页</span>
            <button @click="changePage(form.page + 1)" :disabled="form.page >= totalPages">下一页</button>
            <button @click="changePage(totalPages)" :disabled="form.page >= totalPages">末页</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部导航 - 只在筛选面板关闭时显示 -->
    <BottomNav v-if="!showFilterPanel" />

    <!-- 筛选面板 -->
    <div class="filter-panel" v-if="showFilterPanel">

      <div class="filter-panel-overlay" @click="closeFilterPanel"></div>
      <div class="filter-panel-content" @click.stop>

        <!-- 标题部分 -->
        <div class="filter-panel-header">
          <button class="reset-btn" @click="resetForm" title="重置筛选条件">🔄</button>
          <h3 class="filter-title">筛选</h3>
          <a href="#" class="save-strategy" @click.prevent="saveStrategy">保存策略</a>
        </div>
        <!-- 策略选择区域 -->
        <div class="strategy-selection" v-if="hasStrategies">
          <div class="strategy-label">策略：</div>
          <div class="strategy-tags">
            <div
              v-for="strategy in filteredStrategies"
              :key="strategy.id"
              class="strategy-tag"
              :class="{
                [`strategy-${strategy.type}`]: true,
                'selected': selectedStrategy === strategy.id
              }"
              @click="handleStrategyClick(strategy)"
            >
              {{ strategy.name }}
            </div>
          </div>
        </div>

        <!-- 市场选择 -->
        <div class="market-selection">
          <div class="market-label">地区：</div>
          <div
            class="market-tag"
            :class="{ active: selectedMarket === 'china' }"
            @click="selectMarket('china')"
          >
            <span class="flag-icon flag-icon-cn"></span>
            <span>中国</span>
          </div>
          <div
            class="market-tag"
            :class="{ active: selectedMarket === 'hongkong' }"
            @click="selectMarket('hongkong')"
          >
            <span class="flag-icon flag-icon-hk"></span>
            <span>香港</span>
          </div>
          <div
            class="market-tag"
            :class="{ active: selectedMarket === 'usa' }"
            @click="selectMarket('usa')"
          >
            <span class="flag-icon flag-icon-us"></span>
            <span>美国</span>
          </div>
          <div
            class="market-tag"
            :class="{ active: selectedMarket === 'japan' }"
            @click="selectMarket('japan')"
          >
            <span class="flag-icon flag-icon-jp"></span>
            <span>日本</span>
          </div>
        </div>

        <!-- 筛选条件表单 -->
        <div class="filter-form">
          <!-- PE筛选 -->
          <div class="filter-item">
            <label>PE</label>
            <div class="input-group">
              <input
                type="number"
                placeholder="最小值"
                v-model="form.peMin"
                @input="handleInput('pe')"
              />
              <span>~</span>
              <input
                type="number"
                placeholder="最大值"
                v-model="form.peMax"
                @input="handleInput('pe')"
              />
            </div>
            <div v-if="errors.pe" class="error-message">请输入比最小值更大的值</div>
          </div>

          <!-- ROE筛选 -->
          <div class="filter-item">
            <label>ROE(%)</label>
            <div class="input-group">
              <input
                type="number"
                placeholder="最小值"
                v-model="form.roeMin"
                @input="handleInput('roe')"
              />
              <span>~</span>
              <input
                type="number"
                placeholder="最大值"
                v-model="form.roeMax"
                @input="handleInput('roe')"
              />
            </div>
            <div v-if="errors.roe" class="error-message">请输入比最小值更大的值</div>
          </div>

          <!-- 营收筛选 -->
          <div class="filter-item">
            <label>人均创收(万元)</label>
            <div class="input-group">
              <input
                type="number"
                placeholder="最小值"
                v-model="form.revenueMin"
                @input="handleInput('revenue')"
              />
              <span>~</span>
              <input
                type="number"
                placeholder="最大值"
                v-model="form.revenueMax"
                @input="handleInput('revenue')"
              />
            </div>
            <div v-if="errors.revenue" class="error-message">请输入比最小值更大的值</div>
          </div>

          <!-- 利润筛选 -->
          <div class="filter-item">
            <label>人均创利(万元)</label>
            <div class="input-group">
              <input
                type="number"
                placeholder="最小值"
                v-model="form.profitMin"
                @input="handleInput('profit')"
              />
              <span>~</span>
              <input
                type="number"
                placeholder="最大值"
                v-model="form.profitMax"
                @input="handleInput('profit')"
              />
            </div>
            <div v-if="errors.profit" class="error-message">请输入比最小值更大的值</div>
          </div>

          <!-- 人效筛选 -->
          <div class="filter-item">
            <label>人效(%)</label>
            <div class="input-group">
              <input
                type="number"
                placeholder="最小值"
                v-model="form.profitRevenueRangeMin"
                @input="handleInput('profitRevenueRange')"
              />
              <span>~</span>
              <input
                type="number"
                placeholder="最大值"
                v-model="form.profitRevenueRangeMax"
                @input="handleInput('profitRevenueRange')"
              />
            </div>
            <div v-if="errors.profitRevenueRange" class="error-message">请输入比最小值更大的值</div>
          </div>

          <!-- PEG筛选 -->
          <div class="filter-item">
<!--            <label>股票PEG(市盈率/增长率)</label>-->
            <label>预测PEG(市盈率/增长率)</label>
            <div class="input-group">
              <input
                type="number"
                placeholder="最小值"
                v-model="form.pegMin"
                @input="handleInput('peg')"
              />
              <span>~</span>
              <input
                type="number"
                placeholder="最大值"
                v-model="form.pegMax"
                @input="handleInput('peg')"
              />
            </div>
            <div v-if="errors.peg" class="error-message">请输入比最小值更大的值</div>
          </div>

          <!-- EV筛选 -->
          <div class="filter-item">
            <label>市值(亿)</label>
            <div class="input-group">
              <input
                type="number"
                placeholder="最小值"
                v-model="form.evMin"
                @input="handleInput('ev')"
              />
              <span>~</span>
              <input
                type="number"
                placeholder="最大值"
                v-model="form.evMax"
                @input="handleInput('ev')"
              />
            </div>
            <div v-if="errors.ev" class="error-message">请输入比最小值更大的值</div>
          </div>

          <!-- 上市年限筛选 -->
          <div class="filter-item">
            <label>上市年限(年)</label>
            <div class="input-group">
              <input
                type="number"
                placeholder="最小值"
                v-model="form.ipoYearMin"
                @input="handleInput('ipoYear')"
              />
              <span>~</span>
              <input
                type="number"
                placeholder="最大值"
                v-model="form.ipoYearMax"
                @input="handleInput('ipoYear')"
              />
            </div>
            <div v-if="errors.ipoYear" class="error-message">请输入比最小值更大的值</div>
          </div>
          <!-- 底部按钮 -->
          <div class="filter-panel-footer">
            <button class="selected-btn">已选择({{ selectedCount }})</button>
            <button class="result-btn" @click="handleViewResult">查看结果({{ totalItems }})</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <MessageToast
      v-if="message.show"
      :message="message.text"
      :type="message.type"
      :duration="3000"
    />

    <!-- 确认对话框 -->
    <div class="confirm-dialog-overlay" v-if="showConfirmDialog" @click="handleConfirmDialogCancel">
      <div class="confirm-dialog" @click.stop>
        <div class="dialog-header">
          <h3>{{ confirmDialogConfig.title }}</h3>
        </div>
        <div class="dialog-body">
          <p class="confirm-message">{{ confirmDialogConfig.message }}</p>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="handleConfirmDialogCancel">{{ confirmDialogConfig.cancelText }}</button>
          <button class="btn btn-primary" @click="handleConfirmDialogConfirm">{{ confirmDialogConfig.confirmText }}</button>
        </div>
      </div>
    </div>

    <!-- 保存策略对话框 -->
    <div class="save-strategy-dialog" v-if="showSaveStrategyDialog">
      <div class="dialog-overlay" @click="cancelSaveStrategy"></div>
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>保存策略</h3>
          <button class="close-btn" @click="cancelSaveStrategy">&times;</button>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label>策略名称</label>
            <input
              type="text"
              v-model="strategyForm.name"
              placeholder="请输入策略名称"
              class="form-control"
            />
          </div>
          <div class="form-group">
            <label>备注</label>
            <textarea
              v-model="strategyForm.description"
              placeholder="请输入备注信息"
            ></textarea>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="cancelSaveStrategy">取消</button>
          <button class="btn btn-primary" @click="confirmSaveStrategy">确认</button>
        </div>
      </div>
    </div>

    <!-- 保存指标对话框 -->
    <div class="save-strategy-dialog" v-if="showSaveIndicatorDialog">
      <div class="dialog-overlay" @click="cancelSaveIndicator"></div>
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>保存指标</h3>
          <button class="close-btn" @click="cancelSaveIndicator">&times;</button>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label>指标名称</label>
            <input
              type="text"
              v-model="indicatorForm.name"
              placeholder="请输入指标名称"
              class="form-control"
            />
          </div>
          <div class="form-group">
            <label>备注</label>
            <textarea
              v-model="indicatorForm.description"
              placeholder="请输入备注信息"
              class="form-control"
              rows="3"
            ></textarea>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="cancelSaveIndicator">取消</button>
          <button class="btn btn-primary" @click="confirmSaveIndicator">保存</button>
        </div>
      </div>
    </div>
    <!-- 指标对话框 -->
    <div v-if="showDialog" class="indicator-modal-overlay" @click="onCancel">
      <div class="indicator-modal" @click.stop>
        <div class="indicator-modal-header">
          <h3>指标选择</h3>
          <button class="close-button" @click="onCancel">×</button>
        </div>

        <div class="indicator-dialog">
          <!-- 指标标签 -->
          <div class="indicator-tabs">
            <button
              v-for="(strategyName, index) in (indicatorStrategyNames || [])"
              :key="index"
              class="tab"
              :class="{ active: activeTab === 'tab' + (index + 1) }"
              @click="toggleTab('tab' + (index + 1))"
            >
              {{ strategyName }}
            </button>
            <!-- 如果没有指标策略，显示默认标签 -->
            <button
              v-if="!indicatorStrategyNames || indicatorStrategyNames.length === 0"
              class="tab"
              :class="{ active: activeTab === 'tab1' }"
              @click="toggleTab('tab1')"
            >
              默认指标
            </button>
          </div>

          <!-- 选择指标 -->
          <div class="indicator-selection">
            <div class="selection-header">
              <span>选择指标（已选 {{ (selectedIndicators || []).length }}/9 个）</span>
            </div>
            <div class="checkbox-group">
              <div class="checkbox-row" v-for="indicator in displayedIndicators" :key="indicator.value">
                <label class="checkbox-item">
                  <input
                    type="checkbox"
                    :value="indicator.value"
                    v-model="selectedIndicators"
                    :disabled="selectedIndicators.length >= 9 && !selectedIndicators.includes(indicator.value)"
                    class="checkbox-input"
                  >
                  <span class="checkbox-label">{{ indicator.label }}</span>
                </label>
              </div>

              <!-- 展开/收起控件 -->
              <div v-if="currentIndicators.length > 30" class="expand-controls">
                <button
                  class="expand-btn"
                  @click="toggleShowAllIndicators"
                >
                  {{ showAllIndicators ? '收起' : '展开全部 (' + (currentIndicators.length - 30) + ' 条)' }}
                </button>
              </div>
            </div>
            <div v-if="selectedIndicators.length >= 9" class="indicator-limit">
              <span class="warning-icon">⚠</span> 已达到最大选择数量（9个）
            </div>
          </div>

          <!-- 指标排序 -->
          <div v-if="selectedIndicators.length > 0" class="indicator-order">
            <div class="order-header">
              <span>指标排序（拖拽进行排序，当前按策略中的tableColumns字段排序）</span>
            </div>
            <draggable
              v-model="selectedIndicators"
              handle=".handle"
              item-key="value"
              class="draggable-container"
              @start="onDragStart"
              @end="onDragEnd"
            >
              <template #item="{ element, index }">
                <div class="indicator-item">
                  <span class="handle">☰</span>
                  <span class="indicator-text">{{ getIndicatorLabel(element) }}</span>
                  <span class="indicator-index">{{ index + 1 }}</span>
                  <span
                    class="remove-icon"
                    @click="removeIndicator(element)"
                  >×</span>
                </div>
              </template>
            </draggable>
          </div>

          <div v-else class="indicator-empty">
            <span class="info-icon">ℹ</span> 请先选择指标
          </div>
        </div>

        <div class="indicator-modal-footer">
          <button class="btn btn-info btn-save-indicator" @click="handleSaveIndicatorClick">保存指标</button>
          <button class="btn btn-danger" @click="resetSelection">重置</button>
          <button class="btn btn-secondary" @click="onCancel">取消</button>
          <button class="btn btn-primary" @click="onConfirm">确认</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import draggable from 'vuedraggable'
import BottomNav from '../components/BottomNav.vue'
import MessageToast from '../components/MessageToast.vue'
import { getPxList, apiSaveStrategy, apiSelectStrategy, apiSelectIndicator } from '@/api/FilterView'
export default {
  name: 'FilterView',
  components: {
    BottomNav,
    MessageToast,
    draggable
  },
  directives: {
    tooltip: {
      mounted(el, binding) {
        // 创建tooltip元素
        const tooltip = document.createElement('div')
        tooltip.className = 'custom-tooltip'
        tooltip.textContent = binding.value

        // 设置样式，确保每个tooltip都是独立的
        tooltip.style.position = 'fixed'
        tooltip.style.background = 'rgba(0, 0, 0, 0.9)'
        tooltip.style.color = 'white'
        tooltip.style.padding = '6px 10px'
        tooltip.style.borderRadius = '4px'
        tooltip.style.fontSize = '13px'
        tooltip.style.whiteSpace = 'nowrap'
        tooltip.style.zIndex = '9999'  // 与CSS保持一致的高z-index
        tooltip.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.4)'
        tooltip.style.opacity = '0'
        tooltip.style.transition = 'opacity 0.2s ease, transform 0.2s ease'
        tooltip.style.transform = 'translateY(5px)'
        tooltip.style.display = 'block'
        tooltip.style.pointerEvents = 'none'

        document.body.appendChild(tooltip)

        // 存储tooltip引用
        el._tooltip = tooltip

        // 添加鼠标事件
        el.addEventListener('mouseenter', function() {
          // 确保内容已更新
          if (el._tooltip) {
            el._tooltip.textContent = binding.value
          }

          // 立即显示tooltip
          if (el._tooltip && el.isConnected) {
            const rect = el.getBoundingClientRect()
            const tooltipRect = el._tooltip.getBoundingClientRect()

            // 为股票名称和代码设置不同的位置，确保它们独立显示
            let x, y;
            if (el.classList.contains('stock-code')) {
              // 股票代码tooltip显示在右侧
              x = rect.right + 8
              y = rect.top + rect.height / 2 - tooltipRect.height / 2
            } else {
              // 股票名称tooltip显示在上方
              x = rect.left + rect.width / 2 - tooltipRect.width / 2
              y = rect.top - tooltipRect.height - 8
            }

            // 确保不超出视口边界
            const maxX = window.innerWidth - tooltipRect.width
            const maxY = window.innerHeight - tooltipRect.height
            x = Math.max(0, Math.min(x, maxX))
            y = Math.max(0, Math.min(y, maxY))

            el._tooltip.style.left = `${x}px`
            el._tooltip.style.top = `${y}px`
            el._tooltip.style.opacity = '1'
            el._tooltip.style.transform = 'translateY(0)'
          }
        })

        // 确保tooltip在鼠标移走时立即消失
        el.addEventListener('mouseleave', () => {
          if (el._tooltip) {
            el._tooltip.style.opacity = '0'
            el._tooltip.style.transform = 'translateY(5px)'
          }
        })

        // 处理tooltip超出视口的情况
        el.addEventListener('mousemove', () => {
          if (el._tooltip && el._tooltip.style.opacity === '1') {
            const rect = el.getBoundingClientRect()
            const tooltipRect = el._tooltip.getBoundingClientRect()

            let x, y;
            if (el.classList.contains('stock-code')) {
              x = rect.right + 8
              y = rect.top + rect.height / 2 - tooltipRect.height / 2
            } else {
              x = rect.left + rect.width / 2 - tooltipRect.width / 2
              y = rect.top - tooltipRect.height - 8
            }

            const maxX = window.innerWidth - tooltipRect.width
            const maxY = window.innerHeight - tooltipRect.height
            x = Math.max(0, Math.min(x, maxX))
            y = Math.max(0, Math.min(y, maxY))

            el._tooltip.style.left = `${x}px`
            el._tooltip.style.top = `${y}px`
          }
        })
      },

      updated(el, binding) {
        if (el._tooltip) {
          el._tooltip.textContent = binding.value
        }
      },

      unmounted(el) {
        if (el._tooltip) {
          // 移除前先隐藏，避免突然消失的视觉效果
          el._tooltip.style.opacity = '0'

          // 短暂延迟后再移除DOM元素
          setTimeout(() => {
            if (document.body.contains(el._tooltip)) {
              document.body.removeChild(el._tooltip)
            }
          }, 200)

          delete el._tooltip
        }
      }
    }
  },
  setup() {
    // eslint-disable-next-line no-unused-vars
    const showDialog = ref(false);
    const activeTab = ref('');

    // 确认对话框状态
    const showConfirmDialog = ref(false);
    const confirmDialogConfig = ref({
      title: '',
      message: '',
      confirmText: '确定',
      cancelText: '取消',
      onConfirm: () => {},
      onCancel: () => {}
    });

    // 显示确认对话框
    const showConfirm = (config) => {
      confirmDialogConfig.value = {
        title: '确认操作',
        message: '',
        confirmText: '确定',
        cancelText: '取消',
        onConfirm: () => {},
        onCancel: () => {},
        ...config
      };
      showConfirmDialog.value = true;
    };

    // 隐藏确认对话框
    const hideConfirm = () => {
      showConfirmDialog.value = false;
    };

    // 确认对话框确认按钮点击
    const handleConfirmDialogConfirm = () => {
      if (typeof confirmDialogConfig.value.onConfirm === 'function') {
        confirmDialogConfig.value.onConfirm();
      }
      hideConfirm();
    };

    // 确认对话框取消按钮点击
    const handleConfirmDialogCancel = () => {
      if (typeof confirmDialogConfig.value.onCancel === 'function') {
        confirmDialogConfig.value.onCancel();
      }
      hideConfirm();
    };

    // 切换标签选中状态
    const toggleTab = async (tab) => {
      // 如果点击的是当前选中的标签，则取消选中
      if (activeTab.value === tab) {
        activeTab.value = '';
        // 清空选中的指标
        selectedIndicators.value = [];
        // 重新查询指标数据，确保选择指标区域回到进入对话框时的初始状态
        try {
          await queryIndicatorData();
          console.log('取消选中策略标签，已重新查询指标数据，选择指标区域已回到初始状态');
        } catch (error) {
          console.error('重新查询指标数据失败:', error);
          // 即使查询失败，也清空可用指标，确保UI正确显示
          availableIndicators.value = [];
        }
      } else {
        activeTab.value = tab;

        // 获取当前选中标签对应的策略索引
        const tabIndex = parseInt(tab.replace('tab', '')) - 1;

        // 首先过滤出所有指标策略
        const indicatorStrategies = strategies.value?.filter(strategy => strategy.sorted === 'indicator') || [];

        // 查找对应的指标策略
        if (indicatorStrategies && tabIndex < indicatorStrategies.length) {
          const selectedStrategy = indicatorStrategies[tabIndex];

          // 如果是指标策略，则更新指标列表
          if (selectedStrategy.strategy) {
            console.log('切换到指标策略:', selectedStrategy.name);

            // 从策略中提取指标列表
          const strategyIndicators = [];
          if (selectedStrategy.strategy.tableColumns) {
            // 按照策略中的tableColumns字段顺序遍历指标
            Object.keys(selectedStrategy.strategy.tableColumns).forEach(columnKey => {
              const columnData = selectedStrategy.strategy.tableColumns[columnKey];
              if (columnData.name && columnData.column) {
                // 确保每个指标都有正确的value和label
                strategyIndicators.push({
                  value: columnData.column,  // 使用column字段作为值
                  label: columnData.name,    // 使用name字段作为显示名称
                  name: columnData.name,     // 额外保存name字段以备用
                  column: columnData.column  // 额外保存column字段以备用
                });
              }
            });
          }

          // 如果策略中有指标，则使用策略中的指标
          if (strategyIndicators.length > 0) {
            // 存储完整的指标数据，包括name和column字段
            availableIndicators.value = strategyIndicators;

            // 自动选中策略中包含的指标，并按照策略中的顺序排序
            // 使用Vue的响应式更新方法确保UI更新
            selectedIndicators.value = [...strategyIndicators.map(indicator => indicator.value)];
            console.log('自动选中策略中的指标:', selectedIndicators.value);

            // 确保指标排序区域显示，并按照策略中的顺序进行排序
            console.log('指标排序已按照策略中的tableColumns字段进行排序:', strategyIndicators.map(indicator => indicator.label));
          }

            // 更新动态列配置 - 仅用于UI显示，不影响数据加载
            updateDynamicColumnsFromStrategy(selectedStrategy);
          }
        }
      }
    };

    // 定义指标数据
    const indicatorData = {
      tab1: [
        { value: 'pe', label: '市盈率TTM' },
        { value: 'pb', label: '市净率' },
        { value: 'ps', label: '市销率' },
        { value: 'peg', label: 'PEG指标' },
        { value: 'dividend_yield', label: '股息率' },
        { value: 'ev_ebitda', label: 'EV/EBITDA' },
        { value: 'market_cap', label: '总市值' },
        { value: 'circulating_market_cap', label: '流通市值' }
      ],
      tab2: [
        { value: 'revenue_growth', label: '营收增长率' },
        { value: 'profit_growth', label: '利润增长率' },
        { value: 'net_profit_growth', label: '净利润增长率' },
        { value: 'gross_margin', label: '毛利率' },
        { value: 'net_margin', label: '净利率' },
        { value: 'roe', label: 'ROE' },
        { value: 'roa', label: 'ROA' },
        { value: 'roic', label: 'ROIC' }
      ],
      tab3: [
        { value: 'roe_ttm', label: 'ROE(TTM)' },
        { value: 'roe_avg_3y', label: 'ROE(3年平均)' },
        { value: 'roe_avg_5y', label: 'ROE(5年平均)' },
        { value: 'roe_stability', label: 'ROE稳定性' },
        { value: 'roe_trend', label: 'ROE趋势' },
        { value: 'dupont_analysis', label: '杜邦分析' }
      ],
      tab4: [
        { value: 'revenue_per_employee', label: '人均营收' },
        { value: 'profit_per_employee', label: '人均利润' },
        { value: 'employee_efficiency', label: '人效指标' },
        { value: 'labor_cost_ratio', label: '人工成本占比' },
        { value: 'productivity_growth', label: '生产率增长' }
      ]
    };

    const selectedIndicators = ref([]);

    // 计算当前标签页的指标（优先使用API查询到的真实指标数据）
    const currentIndicators = computed(() => {
      // 如果API查询到了指标数据，则使用真实数据
      if (availableIndicators.value && availableIndicators.value.length > 0) {
        // 将API返回的指标数据转换为选择器需要的格式
        return availableIndicators.value.map(indicator => {
          // 确保指标对象包含完整的字段信息
          return {
            value: indicator.value || indicator.column || indicator.name,
            label: indicator.label || indicator.name || indicator.column,
            name: indicator.name || indicator.label || indicator.column,
            column: indicator.column || indicator.value || indicator.name
          };
        });
      }

      // 否则使用默认的硬编码指标数据
      return Object.values(indicatorData).flat();
    });

    // 计算要显示的指标列表（默认显示30条）
    const displayedIndicators = computed(() => {
      if (showAllIndicators.value) {
        return currentIndicators.value;
      }
      return currentIndicators.value.slice(0, 30);
    });

    // 根据指标值获取标签（优先使用API查询到的真实指标数据）
    const getIndicatorLabel = (value) => {
      console.log('获取指标标签:', value);

      // 如果API查询到了指标数据，则优先使用真实数据
      if (availableIndicators.value && availableIndicators.value.length > 0) {
        // 首先尝试通过value字段查找
        const apiIndicator = availableIndicators.value.find(item =>
          (item.value === value) || (item.column === value) || (item.name === value)
        );
        if (apiIndicator) {
          // 优先使用name字段作为显示标签
          const label = apiIndicator.name || apiIndicator.label || apiIndicator.column || value;
          console.log('API查询到的指标标签:', label);
          return label;
        }
      }

      // 否则使用默认的硬编码指标数据
      const allIndicators = Object.values(indicatorData).flat();
      const indicator = allIndicators.find(item => item.value === value);
      const label = indicator ? indicator.label : value;
      console.log('默认指标标签:', label);
      return label;
    };

    // 移除指标
    const removeIndicator = (value) => {
      const index = selectedIndicators.value.indexOf(value);
      if (index > -1) {
        selectedIndicators.value.splice(index, 1);
      }
    };

    // 拖拽开始事件
    // eslint-disable-next-line no-unused-vars
    const onDragStart = (event) => {
      console.log('开始拖拽指标:', event.item.textContent);
    };

    // 拖拽结束事件
    // eslint-disable-next-line no-unused-vars
    const onDragEnd = (event) => {
      console.log('拖拽结束，当前指标顺序:', selectedIndicators.value.map((value, index) => {
        return `${index + 1}. ${getIndicatorLabel(value)}`;
      }).join(', '));
    };

    // 指标策略名称列表
    const indicatorStrategyNames = ref([]);

    // 点击指标按钮的处理方法
    const handleIndicatorClick = async () => {
      try {
        console.log('开始查询策略数据...');

        // 查询策略数据
        await fetchStrategies();

        // 过滤出指标策略（sorted值为'indicator'，如果没有sorted字段则默认为筛选策略）
        // 添加空值检查
        if (strategies.value) {
          indicatorStrategyNames.value = strategies.value
            .filter(strategy => strategy.sorted === 'indicator')
            .map(strategy => strategy.name);

          console.log('查询到的指标策略名称:', indicatorStrategyNames.value);
        }

        // 查询指标数据
        await queryIndicatorData();

        // 如果筛选表单中有选中的策略，并且该策略是指标策略，则在指标对话框中自动选中对应的标签
        if (selectedStrategy.value && selectedStrategyInfo.value && selectedStrategyInfo.value.sorted === 'indicator') {
          const strategyIndex = indicatorStrategyNames.value.findIndex(name => name === selectedStrategyInfo.value.name);
          if (strategyIndex !== -1) {
            activeTab.value = 'tab' + (strategyIndex + 1);
            console.log('自动选中指标策略标签:', activeTab.value);
          }
        } else {
          // 默认不选择任何指标策略标签
          activeTab.value = '';
          console.log('默认不选择任何指标策略标签');
        }

        // 查询完成后显示指标对话框
        showDialog.value = true;

        console.log('策略和指标查询完成，对话框已显示');
      } catch (error) {
        console.error('处理指标点击时发生错误:', error);
        alert('指标查询失败，请重试');
      }
    };

    // 指标查询方法
    const queryIndicatorData = async () => {
      try {
        console.log('开始执行指标查询...');

        // 构建指标查询参数
        const indicatorParams = {};

        console.log('指标查询参数:', indicatorParams);

        // 调用真实的指标查询API
        const response = await apiSelectIndicator();

        console.log('指标查询完整响应:', response);
        console.log('指标查询响应数据:', response?.data);

        // 根据项目中的API响应结构处理结果
        if (response && response.data) {
          // 检查响应状态
          if (response.data.status === 0) {
            // 处理查询结果
            console.log('指标查询成功，返回数据:', response.data.data);

            // 获取指标数据并回显
            let indicatorData = response.data.data;

            // 兼容不同的响应数据结构，根据用户提供的实际数据格式调整
            if (indicatorData && indicatorData.items) {
              indicatorData = indicatorData.items;
            } else if (indicatorData && indicatorData.data && indicatorData.data.items) {
              indicatorData = indicatorData.data.items;
            }

            // 存储查询到的指标数据
            availableIndicators.value = indicatorData;

            // 显示查询结果统计信息
            console.log('查询到的指标数量:', indicatorData.length);
            console.log('指标详情:', indicatorData);

            // 准备指标列表字符串用于显示
            let indicatorListStr = '查询到的指标列表：\n';
            indicatorData.forEach((indicator, index) => {
              indicatorListStr += `${index + 1}. ${indicator.name || '未知指标'} (${indicator.column || '未知字段名'})\n`;
            });

            // 显示查询结果
            console.log(indicatorListStr);

          } else {
            console.error('指标查询失败，状态码:', response.data.status, '消息:', response.data.msgs);
            alert(`指标查询失败: ${response.data.msgs || '未知错误'}`);
          }
        } else {
          console.error('指标查询响应格式不正确:', response);
          alert('指标查询失败：响应格式不正确');
        }

      } catch (error) {
        console.error('指标查询失败:', error);
        console.error('错误详情:', error.response?.data || error);
        alert('指标查询失败，请检查网络连接');
      }
    };

    // 可用指标列表
    const availableIndicators = ref([]);

    // 控制是否显示全部指标
    const showAllIndicators = ref(false);

    // 切换显示全部指标
    const toggleShowAllIndicators = () => {
      showAllIndicators.value = !showAllIndicators.value;
    };

    // 从选中的指标更新动态列配置
    const updateDynamicColumnsFromSelectedIndicators = () => {
      if (selectedIndicators.value.length === 0) {
        return;
      }

      // 清空现有的动态列配置
      dynamicTableColumns.value = [];

      // 添加基础列：股票名称和区间涨跌幅

      // 根据选中的指标添加对应的列
      selectedIndicators.value.forEach(indicator => {
        // 尝试从API返回的可用指标中查找
        let indicatorInfo = null;
        if (availableIndicators.value && availableIndicators.value.length > 0) {
          indicatorInfo = availableIndicators.value.find(item =>
            item.value === indicator || item.column === indicator || item.name === indicator
          );
        }

        // 如果API中没有找到，则尝试从默认指标数据中查找
        if (!indicatorInfo) {
          // 遍历所有指标数据类别
          for (const category in indicatorData) {
            const found = indicatorData[category].find(item => item.value === indicator);
            if (found) {
              indicatorInfo = found;
              break;
            }
          }
        }

        if (indicatorInfo) {
          dynamicTableColumns.value.push({
            name: indicatorInfo.name || indicatorInfo.label || indicator,
            column: indicatorInfo.column || indicator
          });
        }
      });

      console.log('Updated dynamic columns:', dynamicTableColumns.value);
    };

    // 重置动态列配置到初始状态
    const resetDynamicColumnsToInitial = () => {
      // 设置回默认的动态列配置
      dynamicTableColumns.value = [
        { name: '股票名称', column: 'name' },
        { name: '首次筛选涨跌幅', column: 'pct_chg' },
        { name: 'PE', column: 'pe' },
        { name: 'ROE', column: 'roe' },
        { name: '人均创收', column: 'revenue' },
        { name: '人均创利', column: 'profit' },
        { name: '人效', column: 'profit_revenue' },
        { name: '预测PEG', column: 'peg' },
        { name: '市值', column: 'ev' },
        { name: '资产负债率', column: 'debt_ratio' },
        { name: '股息率', column: 'div_yield' },
        { name: '上市年限', column: 'ipo_date_year' }
      ];
    };

    // 确认选择
    const onConfirm = () => {
      console.log('Selected indicators:', selectedIndicators.value);

      if (selectedIndicators.value.length === 0) {
        // 如果没有选择指标，重置到初始状态
        resetDynamicColumnsToInitial();
      } else {
        // 根据选中的指标更新动态列配置
        updateDynamicColumnsFromSelectedIndicators();
      }

      // 关闭对话框
      showDialog.value = false;
      showAllIndicators.value = false;

      // 执行查询方法显示对应数据
      init();
    };

    // 重置选择
    const resetSelection = () => {
      showConfirm({
        title: '确认重置',
        message: '确定要重置所有选择吗？',
        onConfirm: async () => {
          try {
            // 清空对话框数据
            selectedIndicators.value = [];
            activeTab.value = '';
            showAllIndicators.value = false;

            // 重新查询指标数据，确保回显全部指标
            await queryIndicatorData();

            // 显示重置成功的消息提示
            showMessage('重置成功，已重新加载所有指标', 'success');

            console.log('已重置所有选择并重新查询指标数据');
          } catch (error) {
            console.error('重置过程中发生错误:', error);
            showMessage('重置失败，请重试', 'error');
          }
        }
      });
    };

    // 取消选择
    const onCancel = () => {
      // 只关闭对话框，保留选择状态
      showDialog.value = false;
      showAllIndicators.value = false;
    };

    const form=ref({
      page:1,
      page_size:950,
      market:'',
      previousMarket:'', // 记录上次选择的市场，用于检测变化
      peRange:[null, null],
      roeRange:[null, null],
      revenueRange:[null, null],
      profitRange:[null, null],
      netProfitRange:[null, null],
      evRange:[null, null],
      closeRange:[null, null],
      ipoYearRange:[null, null],
      pxCountRange:[null, null],
      pegRange:[null, null],
      profitRevenueRange:[null, null],
      // 添加表单字段用于验证 - 默认为数字类型
      peMin: null,
      peMax: null,
      roeMin: null,
      roeMax: null,
      revenueMin: null,
      revenueMax: null,
      profitMin: null,
      profitMax: null,
      profitRateMin: null,
      profitRateMax: null,
      profitRevenueRangeMin: null,
      profitRevenueRangeMax: null,
      pegMin: null,
      pegMax: null,
      evMin: null,
      evMax: null,
      ipoYearMin: null,
      ipoYearMax: null,
    })

    // 验证错误状态
    const errors = ref({
      pe: false,
      roe: false,
      revenue: false,
      profit: false,
      profitRate: false,
      profitRevenueRange: false,
      peg: false,
      ev: false,
      listingYears: false,
      ipoYear: false,
    })

    // 保存策略对话框状态
    const showSaveStrategyDialog = ref(false)
    const strategyForm = ref({
      name: '',
      description: '',
      sorted: 'default'  // 默认排序
    })

    // 保存指标对话框状态
    const showSaveIndicatorDialog = ref(false)
    const indicatorForm = ref({
      name: '',
      description: ''
    })

    // 列选择器对话框状态
    const showColumnSelectorDialog = ref(false)

    // 动态数据行列配置数组
    const dynamicTableColumns = ref([
      { name: '股票名称', column: 'name' },
      { name: '首次筛选涨跌幅', column: 'pct_chg' },
      { name: 'PE', column: 'pe' },
      { name: 'ROE', column: 'roe' },
      { name: '人均创收', column: 'revenue' },
      { name: '人均创利', column: 'profit' },
      { name: '人效', column: 'profit_revenue' },
      { name: '预测PEG', column: 'peg' },
      { name: '市值', column: 'ev' },
      { name: '资产负债率', column: 'debt_ratio' },
      { name: '股息率', column: 'div_yield' },
      { name: '上市年限', column: 'ipo_date_year' }
    ])

    // 所有可用列（只保留表格中实际存在的字段）
    const allColumns = ref([
      { key: 'name', label: '股票名称' },
      { key: 'symbol', label: '股票代码' },
      { key: 'pct_chg', label: '涨跌幅' },
      { key: 'pe', label: 'PE' },
      { key: 'roe', label: 'ROE' },
      { key: 'revenue', label: '营收' },
      { key: 'profit', label: '利润' },
      { key: 'profit_revenue', label: '人效' },
      { key: 'peg', label: '预测PEG' },
      { key: 'ev', label: '市值' },
      { key: 'debt_ratio', label: '资产负债率' },
      { key: 'div_yield', label: '股息率' },
      { key: 'ipo_date_year', label: '上市年限' }
    ])

    // 已选列 (默认只选择股票名称)
    const selectedColumns = ref([
      { key: 'name', label: '股票名称' }
    ])

    // 计算可用列
    const availableColumns = computed(() => {
      return allColumns.value.filter(col =>
        !selectedColumns.value.some(selected => selected.key === col.key)
      )
    })

    // 显示列选择器对话框
    const handleShowColumnSelector = () => {
      // 检查表单中的筛选条件，将有值的条件对应的列自动添加到已选择列
      const fieldMap = {
        peRange: { key: 'pe', label: 'PE' },
        roeRange: { key: 'roe', label: 'ROE' },
        revenueRange: { key: 'revenue', label: '营收' },
        profitRange: { key: 'profit', label: '利润' },
        netProfitRange: { key: 'netProfit', label: '净利润' },
        evRange: { key: 'ev', label: '市值' },
        closeRange: { key: 'close', label: '收盘价' },
        ipoYearRange: { key: 'ipo_date_year', label: '上市年限' },
        pxCountRange: { key: 'pxCount', label: '交易天数' },
        pegRange: { key: 'peg', label: '预测PEG' },
        profitRevenueRange: { key: 'profit_revenue', label: '人效' },
        pct_chg: { key: 'pct_chg', label: '涨跌幅' }
      }

      // 检查每个Range字段
      Object.keys(fieldMap).forEach(field => {
        // 对于pct_chg特殊处理，因为它不是Range字段
        if (field === 'pct_chg') {
          // 由于涨跌幅不是用户直接输入的筛选条件，而是默认显示的，我们可以保留这个逻辑
          // 如果需要根据条件动态添加，可以在这里添加相应的判断逻辑
          return;
        }

        // 检查其他Range字段
        if (form.value[field] && form.value[field].length === 2) {
          const [min, max] = form.value[field];
          // 如果有有效数值，则添加对应的列
          if ((min !== null && min !== undefined && min !== '') ||
              (max !== null && max !== undefined && max !== '')) {
            const column = fieldMap[field];
            // 检查该列是否已在selectedColumns中
            const isAlreadySelected = selectedColumns.value.some(col => col.key === column.key);
            if (!isAlreadySelected) {
              selectedColumns.value.push(column);
            }
          }
        }
      })

      showColumnSelectorDialog.value = true
    }

    // 关闭列选择器对话框
    const handleCloseColumnSelector = () => {
      showColumnSelectorDialog.value = false
    }

    // 添加列到已选列
    const addColumn = (column) => {
      // 检查该列是否已在selectedColumns中，避免重复添加
      const isAlreadySelected = selectedColumns.value.some(col => col.key === column.key);
      if (!isAlreadySelected) {
        selectedColumns.value.push({ ...column });
        console.log('已添加列:', column.key);
      }
    }

    // 从已选列中移除
    const removeColumn = (index) => {
      // 确保至少保留一个列
      if (selectedColumns.value.length > 1) {
        selectedColumns.value.splice(index, 1)
      }
    }



    // 消息提示状态
    const message = ref({
      show: false,
      text: '',
      type: 'info'
    })

    // 根据动态列配置渲染表格头部
    const renderTableHeader = () => {
      return dynamicTableColumns.value.map(col => {
        return {
          name: col.name,
          column: col.column,
          sortable: true
        }
      })
    }

    // 根据动态列配置渲染表格数据行
    const renderTableRow = (stock) => {
      return dynamicTableColumns.value.map(col => {
        const value = stock[col.column]
        let className = ''
        let formatType = 'decimal'

        // 根据字段类型设置格式和样式
        switch(col.column) {
          case 'pct_chg':
            formatType = 'percentage'
            className = parseFloat(value) > 0 ? 'positive' : parseFloat(value) < 0 ? 'negative' : ''
            break
          case 'pe':
            formatType = 'multiple'
            break
          case 'roe':
          case 'profit_revenue':
            formatType = 'percentage'
            break
          case 'revenue':
          case 'profit':
          case 'ev':
            formatType = 'decimal'
            break
          case 'debt_ratio':
          case 'div_yield':
            formatType = 'percentage'
            break
          case 'ipo_date_year':
            formatType = 'integer'
            break
          case 'peg':
            formatType = 'decimal'
            break
          default:
            formatType = 'text'
        }

        return {
          value: formatValue(value, formatType),
          className: className
        }
      })
    }

    // 根据策略更新动态列配置
    const updateDynamicColumnsFromStrategy = (strategy) => {
      // 如果是指标策略，则不更新动态列配置，避免影响表格显示
      if (strategy && strategy.sorted === 'indicator') {
        console.log('不更新指标策略的动态列配置，以避免影响表格显示')
        return
      }

      if (strategy && strategy.strategy && strategy.strategy.tableColumns) {
        // 清空数组
        dynamicTableColumns.value = []

        // 将策略中的字段放入数组，但排除股票代码列
        const tableColumns = strategy.strategy.tableColumns
        Object.keys(tableColumns).forEach(columnKey => {
          const columnData = tableColumns[columnKey]
          if (columnData.name && columnData.column && columnData.column !== 'symbol') {
            dynamicTableColumns.value.push({
              name: columnData.name,
              column: columnData.column
            })
          }
        })
        console.log('已从策略更新动态列配置:', dynamicTableColumns.value)
      }
    }

    // 重置为默认列配置
    const resetDynamicColumns = () => {
      dynamicTableColumns.value = [
        { name: '股票名称', column: 'name' },
        { name: '首次筛选涨跌幅', column: 'pct_chg' },
        { name: 'PE', column: 'pe' },
        { name: 'ROE', column: 'roe' },
        { name: '人均创收', column: 'revenue' },
        { name: '人均创利', column: 'profit' },
        { name: '人效', column: 'profit_revenue' },
        { name: '预测PEG', column: 'peg' },
        { name: '市值', column: 'ev' },
        { name: '资产负债率', column: 'debt_ratio' },
        { name: '股息率', column: 'div_yield' },
        { name: '上市年限', column: 'ipo_date_year' }
      ]
      console.log('已重置动态列配置为默认值')
    }

    // 显示消息提示


    // 保存策略方法
    const saveStrategy = () => {
      // 检查表单是否有值
      const hasValue = Object.keys(form.value).some(key => {
        // 检查market字段（地区）是否有值
        if (key === 'market') {
          return form.value[key] !== '' && form.value[key] !== undefined
        }
        // 检查范围字段是否有值
        if (key.endsWith('Range') && Array.isArray(form.value[key])) {
          return form.value[key].some(val => val !== undefined && val !== null)
        }
        // 检查Min/Max字段是否有值
        if (key.endsWith('Min') || key.endsWith('Max')) {
          const value = form.value[key]
          return value !== null && value !== '' && value !== undefined
        }
        return false
      })

      // 如果没有值，提示用户
      if (!hasValue) {
        // 显示友好的提示信息而不是使用alert
        showMessage('请至少选择一个指标再保存策略', 'warning')
        return
      }

      // 如果有值，显示保存策略对话框
      showSaveStrategyDialog.value = true
      strategyForm.value = {
        name: '',
        description: '',
        sorted: ''  // 保持与定义时一致的默认值
      }
    }

    // 消息提示方法
    const showMessage = (text, type = 'info') => {
      // 更新消息状态
      message.value = {
        show: true,
        text,
        type
      }

      // 一段时间后自动隐藏
      setTimeout(() => {
        message.value.show = false
      }, 1500)
    }

    // 处理保存指标按钮点击
    // eslint-disable-next-line no-unused-vars
    const handleSaveIndicatorClick = () => {
      if (selectedIndicators.value.length === 0) {
        showMessage('至少选择一个指标', 'warning')
      } else {
        showSaveIndicatorDialog.value = true
      }
    }

    // 确认保存策略
    const confirmSaveStrategy = async() => {
      // 检查策略名称是否为空
      if (!strategyForm.value.name || strategyForm.value.name.trim() === '') {
        showMessage('请填写策略名称', 'warning')
        return
      }

      // 这里可以添加保存策略的逻辑
      // 将表单数据保存到strategy中
      // 只包含market和各种Range字段
      const formStrategy = {
        name: strategyForm.value.name,
        description: strategyForm.value.description,
        sorted: strategyForm.value.sorted || '',  // 将排序方式添加到表单中
        strategy: {}
      }

      // 创建筛选条件映射，用于匹配字段key和显示名称
      const fieldMap = {
        name: { key: 'name', name: '股票名称' },
        symbol: { key: 'symbol', name: '股票代码' },
        peRange: { key: 'pe', name: 'PE' },
        roeRange: { key: 'roe', name: 'ROE' },
        revenueRange: { key: 'revenue', name: '人均营收' },
        profitRange: { key: 'profit', name: '人均利润' },
        netProfitRange: { key: 'netProfit', name: '净利润' },
        evRange: { key: 'ev', name: '市值' },
        closeRange: { key: 'close', name: '收盘价' },
        ipoYearRange: { key: 'ipo_date_year', name: '上市年限' },
        pxCountRange: { key: 'pxCount', name: '交易天数' },
        pegRange: { key: 'peg', name: '预测PEG' },
        profitRevenueRange: { key: 'profit_revenue', name: '人效' }
      };

      // 先添加所有已选列到策略中
      selectedColumns.value.forEach(column => {
        formStrategy.strategy[column.key] = {
          column: column.key,
          name: column.label,
          value: null
        };
      });

      // 然后检查表单中的筛选条件，将有值的条件更新对应的value
      Object.keys(fieldMap).forEach(field => {
        if (field.endsWith('Range') && form.value[field] && form.value[field].length === 2) {
          const [min, max] = form.value[field];
          const key = fieldMap[field].key;

          // 只更新有有效数值的条件
          if ((min !== null && min !== undefined && min !== '') ||
              (max !== null && max !== undefined && max !== '')) {
            // 如果该列已经在已选列中，则更新其value
          if (formStrategy.strategy[key]) {
            formStrategy.strategy[key].value = form.value[field];
          }
          }
        }
      });

      console.log('保存的策略:', formStrategy)
      // 这里可以添加实际的保存逻辑，比如发送到服务器
      const rest=await apiSaveStrategy(formStrategy)
      if(rest.data.id!==null){
        showMessage('策略保存成功', 'success')
      }else{
        showMessage('策略保存失败', 'error')
      }

      // 关闭对话框
      showSaveStrategyDialog.value = false
    }

    // 取消保存策略
    const cancelSaveStrategy = () => {
      showSaveStrategyDialog.value = false
    }

    // 取消保存指标
    const cancelSaveIndicator = () => {
      showSaveIndicatorDialog.value = false
    }

    // 确认保存指标
    const confirmSaveIndicator = async() => {
      // 检查指标名称是否为空
      if (!indicatorForm.value.name || indicatorForm.value.name.trim() === '') {
        showMessage('请填写指标名称', 'warning')
        return
      }

      // 构建指标数据，使用与保存策略相同的接口格式
      const formIndicator = {
        name: indicatorForm.value.name,
        description: indicatorForm.value.description,
        // 添加sorted字段标识这是指标类型，值固定为indicator
        sorted: 'indicator',
        // 保存选中的指标列表 - 改为对象形式，与保存策略方式一致
        strategy: {}
      }

      // 将选中的指标转换为对象形式，类似于保存策略的方式
      selectedIndicators.value.forEach(indicatorValue => {
        // 查找指标的显示名称
        const indicatorObj = availableIndicators.value.find(indicator => indicator.value === indicatorValue) ||
                            displayedIndicators.value.find(indicator => indicator.value === indicatorValue);

        // 添加到strategy对象中
        formIndicator.strategy[indicatorValue] = {
          column: indicatorValue,
          name: indicatorObj ? indicatorObj.label : indicatorValue,
          value: null
        };
      });

      try {
        // 调用保存策略接口保存指标数据
        const response = await apiSaveStrategy(formIndicator)
        if(response.data && response.data.id !== null) {
          showMessage('指标保存成功', 'success')
          showSaveIndicatorDialog.value = false
          // 清空表单
          indicatorForm.value = {
            name: '',
            description: ''
          }
        } else {
          showMessage('指标保存失败', 'error')
        }
      } catch (error) {
        showMessage('指标保存失败，请重试', 'error')
        console.error('保存指标失败:', error)
      }
    }

    // 验证函数 - 增强版，更好地处理各种输入情况
    const validateRange = (field, minValue, maxValue) => {
      // 处理null值的情况
      minValue = minValue === null ? '' : minValue
      maxValue = maxValue === null ? '' : maxValue

      // 如果两个值都为空，验证通过
      if (minValue === '' && maxValue === '') {
        return true
      }

      // 只有当两个值都有内容时才进行数值范围验证
      if (minValue !== '' && maxValue !== '') {
        const min = parseFloat(minValue)
        const max = parseFloat(maxValue)

        // 检查是否为有效数字
        if (!isNaN(min) && !isNaN(max)) {
          return max >= min
        }
        // 如果有一个不是有效数字，但两个都不为空字符串，则验证失败
        return false
      }

      // 如果只有一个值有内容，验证通过（允许单边筛选）
      return true
    }

    // 处理输入变化
    const handleInput = (field) => {
      const minField = field + 'Min'
      const maxField = field + 'Max'
      // 使用字段本身作为错误字段标识
      const errorField = field
      errors.value[errorField] = !validateRange(field, form.value[minField], form.value[maxField])

      // 确保表单字段是数字类型或null（空值）
      if (form.value[minField] === '') form.value[minField] = null
      if (form.value[maxField] === '') form.value[maxField] = null

      // 更新对应的Range数组
      let rangeField = field === 'profitRate' ? 'profitRateRange' : field === 'profitRevenueRange' ? 'profitRevenueRange' : `${field}Range`

      // 只在用户输入时更新Range数组，使用null作为数字类型的空状态，保持与init函数一致
      form.value[rangeField] = [
        form.value[minField] === null ? null : parseFloat(form.value[minField]),
        form.value[maxField] === null ? null : parseFloat(form.value[maxField])
      ]

      // 当任何一个值有内容且验证通过时，或者两个值都被清除时，自动调用查询
      if (((form.value[minField] !== null || form.value[maxField] !== null) && !errors.value[errorField]) ||
          (form.value[minField] === null && form.value[maxField] === null)) {
          // 自动调用查询
        init()
      }
    }

    // 模拟股票数据
    const stocks = ref([])

    // 创建数组用于保存查询到的所有数据
    const allStocks = ref([])

    // 已移除预览模式，始终显示完整数据

    // 控制筛选框的显示/隐藏状态
    const showFilterPanel = ref(false)

    // 查询策略的数据
    const strategies = ref([])
    const hasStrategies = ref(false)

    // 查询策略方法
    const fetchStrategies = async () => {
      try {
        // 添加调试信息
        console.log('开始获取策略数据...')

        // 调用apiSelectStrategy方法获取策略数据
        const response = await apiSelectStrategy()

        // 处理返回的数据
        // 检查response.data.items是否存在并且有数据
        console.log('完整的response对象:', response)
        console.log('response是否为null:', response === null)
        console.log('response是否为undefined:', response === undefined)
        if (response && response.data && response.data.data) {
          console.log('response.data:', response.data)
          console.log('response.data.data:', response.data.data)
          console.log('response.data.data.items:', response.data.data.items)
          // 检查items数组是否存在且有数据
          if (Array.isArray(response.data.data.items) && response.data.data.items.length > 0) {
            strategies.value = response.data.data.items
            hasStrategies.value = true
            console.log('成功获取策略数据:', strategies.value)
            // 显示第一条策略的详细信息，用于调试
            console.log('第一条策略详情:', strategies.value[0])
            console.log('第一条策略名称:', strategies.value[0]?.name)
          } else {
            // 如果items为空，设置为模拟数据
              strategies.value = [
                { id: 1, name: '测试策略1', type: 'tracking', sorted: 'indicator' },
                { id: 2, name: '测试策略2', type: 'excellent' },
                { id: 3, name: '测试策略3', type: 'rc' }
              ]
            hasStrategies.value = true
            console.log('使用模拟策略数据:', strategies.value)
          }
        } else {
          // 如果没有返回有效的策略数据，显示一些模拟数据用于测试
          strategies.value = [
            { id: 1, name: '测试策略1', type: 'tracking', sorted: 'indicator' },
            { id: 2, name: '测试策略2', type: 'excellent' },
            { id: 3, name: '测试策略3', type: 'rc' }
          ]
          hasStrategies.value = true
          console.log('使用模拟策略数据:', strategies.value)
        }

        console.log('hasStrategies值:', hasStrategies.value)
      } catch (error) {
        console.error('查询策略失败:', error)
        // 错误情况下也显示模拟数据，确保UI正常显示
        strategies.value = [
          {
            id: 1,
            name: '指标策略1',
            type: 'tracking',
            sorted: 'indicator',
            value: {
              peMin: 5,
              peMax: 15,
              roeMin: 10,
              market: 'ZH'
            }
          },
          {
            id: 2,
            name: '指标策略2',
            type: 'excellent',
            sorted: 'indicator'
          }
        ];
        hasStrategies.value = true;
        console.log('错误情况下使用模拟指标策略数据:', strategies.value);
        showMessage('查询策略失败', 'error');
      }
    }

    // 切换筛选框显示状态
    const toggleFilterPanel = async () => {
      showFilterPanel.value = !showFilterPanel.value
      // 当打开筛选面板时，查询策略
      if (showFilterPanel.value) {
        await fetchStrategies()
      }
    }

    // 重置表单数据
    const resetForm = () => {
      // 重置所有表单字段为null
      Object.keys(form.value).forEach(key => {
        if (key.endsWith('Min') || key.endsWith('Max')) {
          form.value[key] = null
        }
      })

      // 重置市场选择
      selectedMarket.value = ''
      form.value.market = ''

      // 重置错误状态
      Object.keys(errors.value).forEach(key => {
        errors.value[key] = false
      })

      // 重置Range数组，统一使用[null, null]格式，与handleInput和init函数保持一致
      form.value.peRange = [null, null]
      form.value.roeRange = [null, null]
      form.value.revenueRange = [null, null]
      form.value.profitRange = [null, null]
      form.value.profitRateRange = [null, null]
      form.value.profitRevenueRange = [null, null]
      form.value.netProfitRange = [null, null]
      form.value.evRange = [null, null]
      form.value.closeRange = [null, null]
      form.value.ipoYearRange = [null, null]
      form.value.pxCountRange = [null, null]
      form.value.pegRange = [null, null]

      // 重置选中的策略
      selectedStrategy.value = null
      selectedStrategyInfo.value = null
      isFromStrategyView.value = false

      console.log('表单已重置，取消选中策略，立即查询所有数据')

      // 立即执行查询，获取所有数据
      init()
    }

    // 关闭筛选面板
    const closeFilterPanel = () => {
      // 关闭面板但不再自动重置表单数据
      showFilterPanel.value = false
      // 重新执行查询，但保持当前筛选条件
      init()
    }

    // 当前选中的市场
    const selectedMarket = ref('') // 默认不选中任何地区

    // 计算选中地区的数量
    const selectedCount = computed(() => {
      return selectedMarket.value ? 1 : 0
    })

    // 当前选中的策略ID
    const selectedStrategy = ref(null)

    // 当前选中的策略完整信息
    const selectedStrategyInfo = ref(null)

    // 是否从策略查看结果
    const isFromStrategyView = ref(false)

    // 计算筛选后的策略列表（只显示筛选策略，不显示指标策略）
    const filteredStrategies = computed(() => {
      return strategies.value.filter(strategy => !strategy.sorted || strategy.sorted !== 'indicator')
    })

    // 处理策略点击事件
    const handleStrategyClick = async (strategy) => {
      console.log('点击了策略:', strategy.name, '策略值:', strategy)

      // 记录策略应用前的表单状态
      console.log('策略应用前的表单状态:', {
        hasActiveFilters: Object.values(form.value).some(val => {
          if (Array.isArray(val) && val.length === 2) return val[0] !== null || val[1] !== null;
          return val !== '' && val !== null && val !== undefined;
        })
      });

      // 检查是否是点击已选中的策略（取消选中）
      if (selectedStrategy.value === strategy.id) {
        console.log('取消选中策略:', strategy.name)

        // 取消选中策略
        selectedStrategy.value = null
        selectedStrategyInfo.value = null
        isFromStrategyView.value = false

        // 重置为默认列配置
        resetDynamicColumns()

        // 清空表单中对应的值
        Object.keys(form.value).forEach(key => {
          if (key.endsWith('Min') || key.endsWith('Max')) {
            form.value[key] = null
          }
        })

        // 重置市场选择
        selectedMarket.value = ''
        form.value.market = ''

        // 重置错误状态
        Object.keys(errors.value).forEach(key => {
          errors.value[key] = false
        })

        // 重置Range数组
        form.value.peRange = []
        form.value.roeRange = []
        form.value.revenueRange = []
        form.value.profitRange = []
        form.value.profitRateRange = []
        form.value.profitRevenueRange = []
        form.value.netProfitRange = []
        form.value.evRange = []
        form.value.closeRange = []
        form.value.ipoYearRange = []
        form.value.pxCountRange = []
        form.value.pegRange = []

        // 显示取消选中消息
        showMessage(`已取消"${strategy.name}"策略`, 'info')

        // 如果指标对话框是打开的，清除选中的标签和指标
        if (showDialog.value) {
          activeTab.value = '';
          // 清空选中的指标，确保选中指标区域被刷新
          selectedIndicators.value = [];
          // 重新查询指标数据，确保选择指标区域回到进入对话框时的初始状态
          try {
            await queryIndicatorData();
            console.log('取消选中策略，已重新查询指标数据，选择指标区域已回到初始状态');
          } catch (error) {
            console.error('重新查询指标数据失败:', error);
            // 即使查询失败，也清空可用指标，确保UI正确显示
            availableIndicators.value = [];
          }
        } else {
          // 即使对话框关闭，也清空选中的指标，确保下次打开时状态正确
          selectedIndicators.value = [];
        }

        // 执行查询，显示所有数据
        init()
        return
      }

      // 更新选中的策略
      selectedStrategy.value = strategy.id
      selectedStrategyInfo.value = strategy

      // 手动重置表单而不调用resetForm()，避免立即查询
      // 重置所有表单字段为null
      Object.keys(form.value).forEach(key => {
        if (key.endsWith('Min') || key.endsWith('Max')) {
          form.value[key] = null
        }
      })

      // 重置市场选择
      selectedMarket.value = ''
      form.value.market = ''

      // 重置错误状态
      Object.keys(errors.value).forEach(key => {
        errors.value[key] = false
      })

      // 重置Range数组
      form.value.peRange = []
      form.value.roeRange = []
      form.value.revenueRange = []
      form.value.profitRange = []
      form.value.profitRateRange = []
      form.value.profitRevenueRange = []
      form.value.netProfitRange = []
      form.value.evRange = []
      form.value.closeRange = []
      form.value.ipoYearRange = []
      form.value.pxCountRange = []
      form.value.pegRange = []

      // 重置策略查看状态
      isFromStrategyView.value = false

      console.log('表单已重置，准备应用策略筛选条件')

      // 记录重置后的表单状态
      console.log('重置后的表单状态:', JSON.stringify(
        Object.keys(form.value).filter(key => key.includes('Range') || key === 'market').map(key => ({
          key,
          value: form.value[key]
        }))
      ));

      // 检查策略是否有效且包含strategy字段
      if (strategy && strategy.strategy) {
        const strategyData = strategy.strategy
        let hasAppliedFilters = false

        // 处理tableColumns结构，这是从API返回的实际数据结构
        if (strategyData.tableColumns) {
          const tableColumns = strategyData.tableColumns

          // 遍历所有表格列
          Object.keys(tableColumns).forEach(columnKey => {
            const columnData = tableColumns[columnKey]
            const { column, value } = columnData

            // 只有当value存在且为数组时才处理
            if (value && Array.isArray(value) && value.length === 2) {
              const [min, max] = value

              // 构建对应的Range字段名
              const rangeField = `${column}Range`
              const minField = `${column}Min`
              const maxField = `${column}Max`

              // 设置Range数组
              if (rangeField in form.value) {
                const prevValue = JSON.stringify(form.value[rangeField]);
                form.value[rangeField] = [
                  min !== null && min !== undefined && min !== '' ? parseFloat(min) : null,
                  max !== null && max !== undefined && max !== '' ? parseFloat(max) : null
                ]
                console.log(`设置${rangeField}: 从${prevValue}变为${JSON.stringify(form.value[rangeField])}`);
                hasAppliedFilters = true
              }

              // 设置对应的表单输入字段
              if (minField in form.value && min !== null && min !== undefined && min !== '') {
                form.value[minField] = min
                console.log(`设置${minField}: ${min}`);
              }
              if (maxField in form.value && max !== null && max !== undefined && max !== '') {
                form.value[maxField] = max
                console.log(`设置${maxField}: ${max}`);
              }
            }
          })
        }

        // 显示成功消息
          showMessage(`已应用"${strategy.name}"策略`, 'success')

          // 从策略更新动态列配置 - 仅用于UI显示，不影响数据加载
          if (strategy.sorted !== 'indicator') {
            updateDynamicColumnsFromStrategy(strategy)
          }

          // 如果这是一个指标策略，并且指标对话框是打开的，则更新指标对话框中的选中标签
          if (strategy.sorted === 'indicator' && showDialog.value) {
            // 过滤出所有指标策略
            const indicatorStrategies = strategies.value?.filter(strat => strat.sorted === 'indicator') || [];
            // 找到当前策略在指标策略列表中的索引
            const strategyIndex = indicatorStrategies.findIndex(strat => strat.id === strategy.id);
            if (strategyIndex !== -1) {
              activeTab.value = 'tab' + (strategyIndex + 1);
              console.log('指标对话框已打开，更新选中的标签:', activeTab.value);

              // 从策略中提取指标列表并更新可用指标
              const strategyIndicators = [];
              if (strategy.strategy.tableColumns) {
                Object.keys(strategy.strategy.tableColumns).forEach(columnKey => {
                  const columnData = strategy.strategy.tableColumns[columnKey];
                  if (columnData.name && columnData.column) {
                    strategyIndicators.push({
                      value: columnData.column,
                      label: columnData.name
                    });
                  }
                });
              }

              // 如果策略中有指标，则使用策略中的指标
              if (strategyIndicators.length > 0) {
                availableIndicators.value = strategyIndicators;
              }
            }
          }

          // 记录策略应用后的表单状态
          console.log('策略应用后的表单状态:', JSON.stringify(
            Object.keys(form.value).filter(key => key.includes('Range') || key === 'market').map(key => ({
              key,
              value: form.value[key]
            }))
          ));

          // 只有当成功应用了筛选条件后才执行查询
          if (hasAppliedFilters) {
            console.log('已成功应用策略筛选条件，准备执行查询')
            init()
          } else {
          console.log('策略中没有有效的筛选条件，不执行查询')
          showMessage('策略中没有有效的筛选条件', 'info')
        }
      } else {
        showMessage('策略数据格式不正确', 'warning')
      }
    }

    // 查看结果按钮点击事件
    const handleViewResult = () => {
      // 如果有选中的策略，则设置从策略查看结果的状态
      if (selectedStrategy.value && selectedStrategyInfo.value) {
        isFromStrategyView.value = true

        // 从策略更新动态列配置
        updateDynamicColumnsFromStrategy(selectedStrategyInfo.value)
      } else {
        isFromStrategyView.value = false

        // 重置为默认列配置
        resetDynamicColumns()
      }

      // 执行查询
      init()
      // 关闭筛选面板
      closeFilterPanel()
    }

    // 选择/取消选择市场
    const selectMarket = (market) => {
      // 如果点击的是当前已选中的市场，则取消选中
      if (selectedMarket.value === market) {
        selectedMarket.value = ''
        form.value.market = ''
      } else {
        // 否则选中新的市场
        selectedMarket.value = market

        // 根据选择的市场更新form.market字段
        const marketMap = {
          'china': 'ZH',
          'hongkong': 'HK',
          'usa': 'US',
          'japan': 'JP'
        }

        form.value.market = marketMap[market] || ''
          console.log('选择市场:', selectedMarket.value, '对应数据标识:', form.value.market)
      }

      // 执行查询
      init()
      console.log('选择的市场:', selectedMarket.value, '对应数据标识:', form.value.market)
    }
    // 总记录数
    const totalItems = ref(0)
    // 总页数
    const totalPages = computed(() => {
      return Math.ceil(totalItems.value / form.value.page_size)
    })

    const sortField = ref('')
    const sortOrder = ref('asc')
    const summaryType = ref('average') // 'average' 或 'median'

    // 辅助函数：将值转换为数字
    const parseNumber = (value) => {
      // 如果值为空或无效，返回null
      if (value === null || value === undefined || value === '' || value === '--') {
        return null;
      }

      // 处理字符串类型的值
      if (typeof value === 'string') {
        // 去除前后空格
        const trimmedValue = value.trim();
        // 去除百分号并转换为小数
        if (trimmedValue.includes('%')) {
          const numValue = parseFloat(trimmedValue.replace('%', ''));
          return isNaN(numValue) ? null : numValue;
        }
        // 转换为数字
        const numValue = parseFloat(trimmedValue);
        return isNaN(numValue) ? null : numValue;
      }

      // 处理数字类型的值
      if (typeof value === 'number') {
        return isNaN(value) ? null : value;
      }

      // 其他类型的值，尝试转换为数字
      const numValue = parseFloat(value);
      return isNaN(numValue) ? null : numValue;
    }

    // 计算平均值的函数
    const calculateAverage = computed(() => {
      // 创建默认值对象，即使stocks为空也能确保所有字段都有初始值
      const average = {
        pct_chg: 0,
        pe: 0,
        roe: 0,
        revenue: 0,
        profit: 0,
        profit_revenue: 0,
        peg: 0,
        ev: 0,
        ipo_date_year: 0,
        debt_ratio: 0,
        div_yield: 0
      }

      if (stocks.value.length === 0) return average

      // 计算每个字段的总和
        stocks.value.forEach(stock => {
          Object.keys(average).forEach(key => {
            const value = parseNumber(stock[key]);
            // 只在值不是null时才累加
            if (value !== null && !isNaN(value)) {
              average[key] += value;
            }
          });
        });

      // 计算平均值
      const count = stocks.value.length
      Object.keys(average).forEach(key => {
        average[key] = average[key] / count
      })

      return average
    })

    // 格式化数据显示
    const formatValue = (value, type) => {
      // 如果值为空或无效，返回"NA"
      if (value === null || value === undefined || value === '') {
        return 'NA'
      }

      // 处理字符串类型的值
      if (typeof value === 'string') {
        // 去除前后空格
        const trimmedValue = value.trim();
        // 检查常见的空值表示
        if (trimmedValue === '' || trimmedValue === '--' || trimmedValue === 'null' || trimmedValue === 'undefined') {
          return 'NA';
        }
        // 转换为数字进行处理
        const numValue = parseFloat(trimmedValue);
        if (!isNaN(numValue)) {
          switch (type) {
            case 'percentage':
              return numValue.toFixed(2) + '%';
            case 'multiple':
              return numValue.toFixed(0) + 'x';
            case 'decimal':
              return numValue.toFixed(2);
            case 'integer':
              return Math.round(numValue);
            default:
              return numValue;
          }
        } else {
          // 非数字字符串原值返回（不是空值）
          return value;
        }
      }

      // 处理数字类型的值
      if (typeof value === 'number') {
        if (isNaN(value)) {
          return 'NA';
        }

        switch (type) {
          case 'percentage':
            return value.toFixed(2) + '%';
          case 'multiple':
            return value.toFixed(0) + 'x';
          case 'decimal':
            return value.toFixed(2);
          case 'integer':
            return Math.round(value);
          default:
            return value;
        }
      }

      // 其他类型的值，原样返回
      return value;
    }

    // 处理排序逻辑 - 修改为在完整数据集上进行排序
    const handleSort = async (field) => {
      // 存储原始数据用于重置排序
      if (!originalAllStocks.value.length && allStocks.value.length > 0) {
        originalAllStocks.value = JSON.parse(JSON.stringify(allStocks.value))
        originalStocks.value = JSON.parse(JSON.stringify(stocks.value))
      }

      // 第三次点击时重置排序
      if (sortField.value === field && sortOrder.value === 'desc') {
        sortField.value = ''
        sortOrder.value = 'asc'
        // 恢复原始数据顺序
        if (originalAllStocks.value.length > 0) {
          allStocks.value = JSON.parse(JSON.stringify(originalAllStocks.value))
          // 重新分页
          applyPagination()
        } else {
          stocks.value = JSON.parse(JSON.stringify(originalStocks.value))
        }
      } else if (sortField.value === field && sortOrder.value === 'asc') {
        // 第二次点击时切换为倒序
        sortOrder.value = 'desc'
        if (allStocks.value.length > 0) {
          // 在完整数据集上排序
          allStocks.value.sort((a, b) => {
            const valA = parseNumber(a[field])
            const valB = parseNumber(b[field])
            // 处理null值，让null排在最后，无论升序还是降序
            if (valA === null && valB === null) return 0
            if (valA === null) return 1
            if (valB === null) return -1
            // 降序排列
            return valB - valA
          })
          // 重新分页
          applyPagination()
        } else {
          // 如果没有完整数据，则在当前数据上排序
          stocks.value.sort((a, b) => {
            const valA = parseNumber(a[field])
            const valB = parseNumber(b[field])
            // 处理null值，让null排在最后，无论升序还是降序
            if (valA === null && valB === null) return 0
            if (valA === null) return 1
            if (valB === null) return -1
            // 降序排列
            return valB - valA
          })
        }
      } else {
        // 第一次点击时设置为正序
        sortField.value = field
        sortOrder.value = 'asc'
        if (allStocks.value.length > 0) {
          // 在完整数据集上排序
          allStocks.value.sort((a, b) => {
            const valA = parseNumber(a[field])
            const valB = parseNumber(b[field])
            // 处理null值，让null排在最后，无论升序还是降序
            if (valA === null && valB === null) return 0
            if (valA === null) return 1
            if (valB === null) return -1
            // 升序排列
            return valA - valB
          })
          // 重新分页
          applyPagination()
        } else {
          // 如果没有完整数据，则在当前数据上排序
          stocks.value.sort((a, b) => {
            const valA = parseNumber(a[field])
            const valB = parseNumber(b[field])
            // 处理null值，让null排在最后，无论升序还是降序
            if (valA === null && valB === null) return 0
            if (valA === null) return 1
            if (valB === null) return -1
            // 升序排列
            return valA - valB
          })
        }
      }
    }

    // 计算中位数的函数
    const calculateMedian = computed(() => {
      // 创建默认值对象，即使stocks为空也能确保所有字段都有初始值
      const median = {
        pct_chg: 0,
        pe: 0,
        roe: 0,
        revenue: 0,
        profit: 0,
        profit_revenue: 0,
        peg: 0,
        ev: 0,
        ipo_date_year: 0,
        debt_ratio: 0,
        div_yield: 0
      };

      // 对每个字段计算中位数
      Object.keys(median).forEach(key => {
        // 创建排序后的数组副本，先将所有值转换为数字并过滤掉null值
        const validValues = [...stocks.value]
          .map(stock => parseNumber(stock[key]))
          .filter(value => value !== null && !isNaN(value));

        // 对有效数据进行排序
        const sortedValues = [...validValues].sort((a, b) => a - b);
        const length = sortedValues.length;

        if (length > 0) {
          if (length % 2 === 0) {
            // 偶数个元素，取中间两个数的平均值
            median[key] = (sortedValues[length / 2 - 1] + sortedValues[length / 2]) / 2;
          } else {
            // 奇数个元素，取中间的数
            median[key] = sortedValues[Math.floor(length / 2)];
          }
        } else {
          // 如果没有有效数据，保持默认值0
          median[key] = 0;
        }
      });

      return median;
    });

    // 当前显示的汇总数据（平均值或中位数）
    const currentSummary = computed(() => {
      return summaryType.value === 'average' ? calculateAverage.value : calculateMedian.value;
    });

    // 切换汇总类型（平均值/中位数）
    const toggleSummaryType = () => {
      summaryType.value = summaryType.value === 'average' ? 'median' : 'average';
    };

    // 存储原始数据用于重置排序
    const originalStocks = ref([])

    // 存储原始完整数据用于重置排序
    const originalAllStocks = ref([])

    // 分页应用函数
    const applyPagination = () => {
      // 根据当前页码和每页显示数量进行分页
      const startIndex = (form.value.page - 1) * form.value.page_size;
      const endIndex = Math.min(startIndex + form.value.page_size, allStocks.value.length);
      stocks.value = allStocks.value.slice(startIndex, endIndex);
      // 更新总记录数
      totalItems.value = allStocks.value.length;
    }

    // 查询状态标志，用于防止重复查询
    const isQuerying = ref(false)

    // 客户端筛选函数 - 确保数据符合筛选条件
    const applyClientFilters = (data, filters) => {
      return data.filter(item => {
        // 检查ROE筛选条件
        if (filters.roeRange && filters.roeRange.length === 2) {
          const roeValue = parseNumber(item.roe);
          const [min, max] = filters.roeRange;

          // 如果ROE值不存在或不是有效数字，且有筛选条件，则过滤掉该数据
          if (roeValue === null || isNaN(roeValue)) {
            return false;
          }

          // 应用最小值筛选
          if (min !== null && roeValue < min) {
            return false;
          }

          // 应用最大值筛选
          if (max !== null && roeValue > max) {
            return false;
          }
        }

        // 检查PE筛选条件
        if (filters.peRange && filters.peRange.length === 2) {
          const peValue = parseNumber(item.pe);
          const [min, max] = filters.peRange;

          if (peValue !== null && !isNaN(peValue)) {
            if (min !== null && peValue < min) return false;
            if (max !== null && peValue > max) return false;
          } else if (min !== null || max !== null) {
            return false; // 如果有筛选条件但值无效，则过滤掉
          }
        }

        // 检查预测PE(PEG)筛选条件
        if (filters.pegRange && filters.pegRange.length === 2) {
          const pegValue = parseNumber(item.peg);
          const [min, max] = filters.pegRange;

          if (pegValue !== null && !isNaN(pegValue)) {
            if (min !== null && pegValue < min) return false;
            if (max !== null && pegValue > max) return false;
          } else if (min !== null || max !== null) {
            return false; // 如果有筛选条件但值无效，则过滤掉
          }
        }

        // 检查市值(EV)筛选条件
        if (filters.evRange && filters.evRange.length === 2) {
          const evValue = parseNumber(item.ev);
          const [min, max] = filters.evRange;

          if (evValue !== null && !isNaN(evValue)) {
            if (min !== null && evValue < min) return false;
            if (max !== null && evValue > max) return false;
          } else if (min !== null || max !== null) {
            return false; // 如果有筛选条件但值无效，则过滤掉
          }
        }

        // 检查上市年限筛选条件
        if (filters.ipoYearRange && filters.ipoYearRange.length === 2) {
          const ipoYearValue = parseNumber(item.ipo_date_year);
          const [min, max] = filters.ipoYearRange;

          if (ipoYearValue !== null && !isNaN(ipoYearValue)) {
            if (min !== null && ipoYearValue < min) return false;
            if (max !== null && ipoYearValue > max) return false;
          } else if (min !== null || max !== null) {
            return false; // 如果有筛选条件但值无效，则过滤掉
          }
        }

        // 检查营收筛选条件
        if (filters.revenueRange && filters.revenueRange.length === 2) {
          const revenueValue = parseNumber(item.revenue);
          const [min, max] = filters.revenueRange;

          if (revenueValue !== null && !isNaN(revenueValue)) {
            if (min !== null && revenueValue < min) return false;
            if (max !== null && revenueValue > max) return false;
          } else if (min !== null || max !== null) {
            return false; // 如果有筛选条件但值无效，则过滤掉
          }
        }

        // 检查利润筛选条件
        if (filters.profitRange && filters.profitRange.length === 2) {
          const profitValue = parseNumber(item.profit);
          const [min, max] = filters.profitRange;

          if (profitValue !== null && !isNaN(profitValue)) {
            if (min !== null && profitValue < min) return false;
            if (max !== null && profitValue > max) return false;
          } else if (min !== null || max !== null) {
            return false; // 如果有筛选条件但值无效，则过滤掉
          }
        }

        // 检查人效筛选条件
        if (filters.profitRevenueRange && filters.profitRevenueRange.length === 2) {
          const profitRevenueValue = parseNumber(item.profit_revenue);
          const [min, max] = filters.profitRevenueRange;

          if (profitRevenueValue !== null && !isNaN(profitRevenueValue)) {
            if (min !== null && profitRevenueValue < min) return false;
            if (max !== null && profitRevenueValue > max) return false;
          } else if (min !== null || max !== null) {
            return false; // 如果有筛选条件但值无效，则过滤掉
          }
        }

        // 检查净利润筛选条件
        if (filters.netProfitRange && filters.netProfitRange.length === 2) {
          const netProfitValue = parseNumber(item.netProfit);
          const [min, max] = filters.netProfitRange;

          if (netProfitValue !== null && !isNaN(netProfitValue)) {
            if (min !== null && netProfitValue < min) return false;
            if (max !== null && netProfitValue > max) return false;
          } else if (min !== null || max !== null) {
            return false; // 如果有筛选条件但值无效，则过滤掉
          }
        }

        // 检查收盘价筛选条件
        if (filters.closeRange && filters.closeRange.length === 2) {
          const closeValue = parseNumber(item.close);
          const [min, max] = filters.closeRange;

          if (closeValue !== null && !isNaN(closeValue)) {
            if (min !== null && closeValue < min) return false;
            if (max !== null && closeValue > max) return false;
          } else if (min !== null || max !== null) {
            return false; // 如果有筛选条件但值无效，则过滤掉
          }
        }

        // 检查交易天数筛选条件
        if (filters.pxCountRange && filters.pxCountRange.length === 2) {
          const pxCountValue = parseNumber(item.pxCount);
          const [min, max] = filters.pxCountRange;

          if (pxCountValue !== null && !isNaN(pxCountValue)) {
            if (min !== null && pxCountValue < min) return false;
            if (max !== null && pxCountValue > max) return false;
          } else if (min !== null || max !== null) {
            return false; // 如果有筛选条件但值无效，则过滤掉
          }
        }

        // 如果通过所有筛选条件，则保留该数据
        return true;
      });
    }

    // 标记是否已经加载了完整数据
    const hasLoadedFullData = ref(false);

    // 完整的原始数据缓存，用于客户端筛选
    const cachedAllData = ref([]);

    // 加载完整数据的方法
    const loadFullData = async () => {
      try {
        isQuerying.value = true;
        console.log('开始加载完整数据...');

        // 发送请求获取完整数据，不包含筛选条件但可以包含市场选择
          // 创建一个新的对象用于请求参数，不直接修改form对象的值
          const requestData = {
              page: form.value.page,
              page_size: form.value.page_size,
              market: form.value.market || '', // 使用空字符串代替null，避免影响表单原始数据
              // 添加筛选条件，严格按照API要求的数组格式
              peRange: form.value.peRange && form.value.peRange.length === 2 ? form.value.peRange : [null, null],
              roeRange: form.value.roeRange && form.value.roeRange.length === 2 ? form.value.roeRange : [null, null],
              revenueRange: form.value.revenueRange && form.value.revenueRange.length === 2 ? form.value.revenueRange : [null, null],
              profitRange: form.value.profitRange && form.value.profitRange.length === 2 ? form.value.profitRange : [null, null],
              profitRevenueRange: form.value.profitRevenueRange && form.value.profitRevenueRange.length === 2 ? form.value.profitRevenueRange : [null, null],
              netProfitRange: form.value.netProfitRange && form.value.netProfitRange.length === 2 ? form.value.netProfitRange : [null, null],
              evRange: form.value.evRange && form.value.evRange.length === 2 ? form.value.evRange : [null, null],
              closeRange: form.value.closeRange && form.value.closeRange.length === 2 ? form.value.closeRange : [null, null],
              ipoYearRange: form.value.ipoYearRange && form.value.ipoYearRange.length === 2 ? form.value.ipoYearRange : [null, null],
              pxCountRange: form.value.pxCountRange && form.value.pxCountRange.length === 2 ? form.value.pxCountRange : [null, null],
              pegRange: form.value.pegRange && form.value.pegRange.length === 2 ? form.value.pegRange : [null, null],
          }

        const rest = await getPxList(requestData);
        console.log('完整数据加载完成，响应状态:', rest?.status);

        // 处理响应数据
        let fetchedData = [];
        if (rest && rest.data && typeof rest.data === 'object') {
          // 尝试从不同结构获取数据
          if (rest.data.data && rest.data.data.items && Array.isArray(rest.data.data.items)) {
            fetchedData = rest.data.data.items;
          } else if (Array.isArray(rest.data.items)) {
            fetchedData = rest.data.items;
          }
        }

        // 如果获取到数据，更新缓存
        if (fetchedData.length > 0) {
          cachedAllData.value = fetchedData;
          hasLoadedFullData.value = true;
          console.log(`成功加载${fetchedData.length}条完整数据`);
        } else {
          // 如果没有获取到数据，使用模拟数据
          console.log('未获取到完整数据，使用模拟数据');
          setMockData();
          cachedAllData.value = [...allStocks.value];
          hasLoadedFullData.value = true;
        }
      } catch (error) {
        console.error('加载完整数据失败:', error);
        // 出错时使用模拟数据
        setMockData();
        cachedAllData.value = [...allStocks.value];
        hasLoadedFullData.value = true;
      } finally {
        isQuerying.value = false;
      }
    };

    // 页面挂载时自动加载数据
    onMounted(async () => {
      console.log('组件挂载完成，开始加载数据...');
      await init();
    });

    // 初始化方法 - 加载股票数据
    const init = async () => {
      // 防止重复查询
      if (isQuerying.value) {
        console.log('查询正在进行中，已阻止重复查询')
        return
      }

      try {
        isQuerying.value = true;

        // 准备当前筛选条件
        const currentFilters = {
          page: form.value.page,
          page_size: form.value.page_size,
          market: form.value.market || '',
          peRange: form.value.peRange && form.value.peRange.length === 2 ? form.value.peRange : [null, null],
          roeRange: form.value.roeRange && form.value.roeRange.length === 2 ? form.value.roeRange : [null, null],
          revenueRange: form.value.revenueRange && form.value.revenueRange.length === 2 ? form.value.revenueRange : [null, null],
          profitRange: form.value.profitRange && form.value.profitRange.length === 2 ? form.value.profitRange : [null, null],
          profitRevenueRange: form.value.profitRevenueRange && form.value.profitRevenueRange.length === 2 ? form.value.profitRevenueRange : [null, null],
          netProfitRange: form.value.netProfitRange && form.value.netProfitRange.length === 2 ? form.value.netProfitRange : [null, null],
          evRange: form.value.evRange && form.value.evRange.length === 2 ? form.value.evRange : [null, null],
          closeRange: form.value.closeRange && form.value.closeRange.length === 2 ? form.value.closeRange : [null, null],
          ipoYearRange: form.value.ipoYearRange && form.value.ipoYearRange.length === 2 ? form.value.ipoYearRange : [null, null],
          pxCountRange: form.value.pxCountRange && form.value.pxCountRange.length === 2 ? form.value.pxCountRange : [null, null],
          pegRange: form.value.pegRange && form.value.pegRange.length === 2 ? form.value.pegRange : [null, null],
        };

        // 检查市场是否改变，如果改变需要重新加载完整数据
        const marketChanged = currentFilters.market !== form.value.previousMarket;

        // 如果还没有加载完整数据或市场发生变化，则加载完整数据
        if (!hasLoadedFullData.value || marketChanged) {
          form.value.previousMarket = currentFilters.market;
          await loadFullData();
        }

        console.log('应用客户端筛选条件');
        // 使用缓存数据进行客户端筛选
        const filteredData = applyClientFilters(cachedAllData.value, currentFilters);

        // 更新总数据和分页
        allStocks.value = filteredData;
        totalItems.value = filteredData.length;

        // 应用分页
        applyPagination();

        // 保存原始数据用于排序重置
        originalAllStocks.value = JSON.parse(JSON.stringify(allStocks.value));

        console.log(`筛选完成，共${totalItems.value}条数据符合条件`);

      } catch (error) {
        console.error('初始化数据失败:', error);
        // 出错时使用模拟数据
        setMockData();
      } finally {
        isQuerying.value = false;
      }
    }

    // 另一个可能的函数定义...
    const anotherFunction = () => {
      try {
        // 应用客户端筛选到模拟数据
        if (hasActiveFilters) {
          console.log('对模拟数据应用客户端筛选条件');
          allStocks.value = applyClientFilters(allStocks.value, requestData);
          applyPagination();
          totalItems.value = allStocks.value.length;
        }
      } catch (error) {
        console.error('加载股票数据失败:', error.message || error);
        console.error('错误详情:', error.response?.data || error);
        // 发生错误时设置模拟数据
        setMockData();
      } finally {
        // 确保无论成功失败都将查询状态重置为false
        isQuerying.value = false;
      }
    };

    // 设置模拟数据的方法，提供丰富的演示数据
    const setMockData = () => {
      // 生成模拟数据
      const mockStocks = [];
      const stockCount = 50; // 生成50条模拟数据用于演示

      // 更丰富的股票样本数据，覆盖不同行业和特性
      // const sampleData = [
      //   { symbol: '600519', name: '贵州茅台', industry: '白酒', pct_chg: 2.65, pe: 35.6, roe: 32.5, revenue: 120, profit: 55, profit_revenue: 45.8, peg: 1.2, ev: 26000, ipo_date_year: 20 },
      //   { symbol: '000858', name: '五粮液', industry: '白酒', pct_chg: 3.12, pe: 28.3, roe: 28.7, revenue: 85, profit: 32, profit_revenue: 37.6, peg: 1.1, ev: 12000, ipo_date_year: 18 },
      //   { symbol: '002594', name: '比亚迪', industry: '新能源汽车', pct_chg: -1.45, pe: 78.9, roe: 7.6, revenue: 420, profit: 15, profit_revenue: 3.6, peg: 2.5, ev: 8500, ipo_date_year: 15 },
      //   { symbol: '000333', name: '美的集团', industry: '家电', pct_chg: 1.23, pe: 14.5, roe: 24.8, revenue: 380, profit: 32, profit_revenue: 8.4, peg: 0.7, ev: 5800, ipo_date_year: 10 },
      //   { symbol: '600036', name: '招商银行', industry: '银行', pct_chg: 0.89, pe: 6.7, roe: 15.6, revenue: 260, profit: 105, profit_revenue: 40.4, peg: 0.4, ev: 10500, ipo_date_year: 25 },
      //   { symbol: '601318', name: '中国平安', industry: '保险', pct_chg: -0.56, pe: 8.9, roe: 12.3, revenue: 890, profit: 145, profit_revenue: 16.3, peg: 0.6, ev: 11800, ipo_date_year: 18 },
      //   { symbol: '000001', name: '平安银行', industry: '银行', pct_chg: 1.02, pe: 5.3, roe: 10.8, revenue: 180, profit: 65, profit_revenue: 36.1, peg: 0.5, ev: 2800, ipo_date_year: 22 },
      //   { symbol: '002415', name: '海康威视', industry: '安防设备', pct_chg: 2.15, pe: 23.4, roe: 18.7, revenue: 165, profit: 32, profit_revenue: 19.4, peg: 0.9, ev: 4200, ipo_date_year: 12 },
      //   { symbol: '300750', name: '宁德时代', industry: '电池', pct_chg: -2.36, pe: 125.8, roe: 10.5, revenue: 580, profit: 38, profit_revenue: 6.6, peg: 3.2, ev: 13500, ipo_date_year: 6 },
      //   { symbol: '600900', name: '长江电力', industry: '电力', pct_chg: 0.42, pe: 19.8, roe: 15.2, revenue: 58, profit: 24, profit_revenue: 41.4, peg: 1.0, ev: 5800, ipo_date_year: 20 }
      // ];

      // 生成更多样例数据，并确保每个股票都有唯一的代码
      // for (let i = 0; i < stockCount; i++) {
      //   // 复制样例数据，并添加一些随机变化
      //   const sampleIndex = i % sampleData.length;
      //   const baseData = { ...sampleData[sampleIndex] };
      //
      //   // 为股票生成唯一的代码后缀
      //   const uniqueCode = baseData.symbol + (i >= sampleData.length ? (i % 100).toString().padStart(2, '0') : '');
      //
      //   // 添加一些随机变化，但保持数据的整体风格
      //   const randomFactor = 0.9 + Math.random() * 0.2; // 0.9-1.1之间的随机因子
      //   mockStocks.push({
      //     symbol: uniqueCode,
      //     name: baseData.name + (i >= sampleData.length ? '(' + (i % 10) + ')' : ''),
      //     industry: baseData.industry,
      //     pct_chg: (baseData.pct_chg * randomFactor).toFixed(2),
      //     pe: (baseData.pe * randomFactor).toFixed(0),
      //     roe: (baseData.roe * randomFactor).toFixed(2),
      //     revenue: (baseData.revenue * randomFactor).toFixed(0),
      //     profit: (baseData.profit * randomFactor).toFixed(0),
      //     profit_revenue: (baseData.profit_revenue * randomFactor).toFixed(2),
      //     peg: (baseData.peg * randomFactor).toFixed(2),
      //     ev: (baseData.ev * randomFactor).toFixed(0),
      //     ipo_date_year: baseData.ipo_date_year
      //   });
      // }

      // 保存完整的模拟数据
      // allStocks.value = mockStocks;
      //
      // // 根据当前页码和每页显示数量进行分页
      // const startIndex = (form.value.page - 1) * form.value.page_size;
      // const endIndex = Math.min(startIndex + form.value.page_size, mockStocks.length);
      //
      // stocks.value = mockStocks.slice(startIndex, endIndex);
      // totalItems.value = mockStocks.length;
      //
      // // 保存原始数据用于排序重置
      // originalStocks.value = JSON.parse(JSON.stringify(stocks.value));
      // originalAllStocks.value = JSON.parse(JSON.stringify(allStocks.value));
      // console.log('使用模拟数据，总条数:', totalItems.value);
    }

    // 切换页码
    const changePage = (newPage) => {
      if (newPage < 1) newPage = 1;
      if (newPage > totalPages.value) newPage = totalPages.value;

      form.value.page = newPage;

      // 如果有完整数据，直接在客户端进行分页，否则重新请求数据
      if (allStocks.value.length > 0) {
        applyPagination();
      } else {
        init(); // 重新加载数据
      }
    }

    // 切换每页显示数量
    const onPageSizeChange = () => {
      form.value.page = 1; // 重置为第一页
      init(); // 重新加载数据
    }

    // 使用Vue的onMounted生命周期钩子调用初始化方法
    onMounted(() => {
      init();
    })

    return {
      stocks,
      sortField,
      sortOrder,
      summaryType,
      calculateAverage,
      calculateMedian,
      currentSummary,
      formatValue,
      handleSort,
      toggleSummaryType,
      form,
      errors,
      handleInput,
      totalItems,
      totalPages,
      changePage,
      onPageSizeChange,
      showFilterPanel,
      toggleFilterPanel,
      toggleTab,
      closeFilterPanel,
      selectedMarket,
      selectMarket,
      selectedCount,
      handleViewResult,
      resetForm,
      // 消息提示相关
      message,
      showMessage,
      // 保存策略相关
      showSaveStrategyDialog,
      strategyForm,
      saveStrategy,
      confirmSaveStrategy,
      cancelSaveStrategy,
      // 保存指标相关
      showSaveIndicatorDialog,
      indicatorForm,
      cancelSaveIndicator,
      confirmSaveIndicator,
      handleSaveIndicatorClick,
      // 查询策略相关
      strategies,
      hasStrategies,
      handleStrategyClick,
      selectedStrategy,
      // 筛选策略列表（只显示筛选策略）
      filteredStrategies,
      // 新增完整数据集和分页函数
      allStocks,
      applyPagination,
      // 列选择器相关
      showColumnSelectorDialog,
      handleShowColumnSelector,
      handleCloseColumnSelector,
      selectedColumns,
      availableColumns,
      addColumn,
      removeColumn,
      // 动态列配置相关
      renderTableHeader,
      renderTableRow,
      updateDynamicColumnsFromStrategy,
      resetDynamicColumns,
      // 指标选择器相关
      showDialog,
      activeTab,
      currentIndicators,
      displayedIndicators,
      selectedIndicators,
      onConfirm,
      onCancel,
      resetSelection,
      getIndicatorLabel,
      removeIndicator,
      showAllIndicators,
      toggleShowAllIndicators,
      indicatorStrategyNames,
      // 确认对话框相关
      showConfirmDialog,
      confirmDialogConfig,
      handleConfirmDialogConfirm,
      handleConfirmDialogCancel,
      // 指标查询相关
      handleIndicatorClick,
      queryIndicatorData
    }
  }
}</script>

<style scoped>
  /* ===== 指标对话框样式 - PC与H5兼容优化 ===== */

  /* 模态层基础样式 */
  .indicator-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    padding: 20px;
    box-sizing: border-box;
  }

  /* 模态对话框容器 */
  .indicator-modal {
    background-color: white;
    border-radius: 12px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
    max-width: 680px;
    width: 100%;
    max-height: 85vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }

  /* 模态头部 */
  .indicator-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
    background-color: #fafafa;
  }

  .indicator-modal-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #1f2937;
  }

  .close-button {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #6b7280;
    padding: 8px;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    transition: all 0.2s ease;
  }

  .close-button:hover {
    color: #374151;
    background-color: #f3f4f6;
  }

  /* 模态底部 */
  .indicator-modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 20px 24px;
    border-top: 1px solid #f0f0f0;
    background-color: #fafafa;
  }

  /* 保存指标按钮样式 */
  .btn-save-indicator {
    margin-right: auto;
  }

  /* 对话框内容区域 */
  .indicator-dialog {
    flex: 1;
    padding: 24px;
    overflow-y: auto;
    min-height: 200px;
  }

  /* 标签页样式 */
  .indicator-tabs {
    display: flex;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    margin-bottom: 24px;
    background-color: #f9fafb;
    overflow: hidden;
  }

  .tab {
    flex: 1;
    padding: 12px 16px;
    text-align: center;
    border: none;
    background: none;
    cursor: pointer;
    font-size: 14px;
    color: #6b7280;
    transition: all 0.3s ease;
    border-right: 1px solid #e5e7eb;
    font-weight: 500;
  }

  .tab:last-child {
    border-right: none;
  }

  .tab.active {
    background-color: #3b82f6;
    color: white;
    font-weight: 600;
  }

  .tab:hover:not(.active) {
    background-color: #f3f4f6;
    color: #374151;
  }

  /* 选择区域样式 */
  .indicator-selection {
    margin-bottom: 24px;
  }

  .selection-header {
    font-size: 15px;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 16px;
    padding: 8px 0;
  }

  .checkbox-group {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
  }

  .checkbox-item {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    border: 2px solid #e5e7eb;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    background-color: white;
    min-height: 48px;
  }

  .checkbox-item:hover {
    border-color: #3b82f6;
    background-color: #f0f9ff;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
  }

  .checkbox-input {
    margin-right: 12px;
    width: 18px;
    height: 18px;
    accent-color: #3b82f6;
  }

  .checkbox-label {
    font-size: 14px;
    color: #374151;
    font-weight: 500;
    line-height: 1.4;
  }

  /* 展开/收起控件样式 */
  .expand-controls {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #e5e7eb;
    display: flex;
    justify-content: center;
  }

  .expand-btn {
    background-color: #f9fafb;
    color: #6b7280;
    border: 2px solid #e5e7eb;
    border-radius: 8px;
    padding: 10px 20px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.3s ease;
  }

  .expand-btn:hover {
    background-color: #f3f4f6;
    border-color: #d1d5db;
    color: #374151;
  }

  /* 排序区域样式 */
  .indicator-order {
    margin-bottom: 24px;
  }

  .order-header {
    font-size: 15px;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 16px;
    padding: 8px 0;
  }

  .draggable-container {
    min-height: 60px;
    border: 2px solid #e5e7eb;
    border-radius: 8px;
    padding: 12px;
    background-color: #f9fafb;
  }

  .indicator-item {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    border: 1px solid #e5e7eb;
    border-radius: 6px;
    margin-bottom: 8px;
    background-color: white;
    transition: all 0.3s ease;
    cursor: move;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  }

  .indicator-item:hover {
    border-color: #3b82f6;
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.15);
    transform: translateY(-1px);
  }

  .handle {
    margin-right: 16px;
    cursor: move;
    color: #9ca3af;
    font-size: 18px;
    padding: 4px;
    border-radius: 4px;
    transition: all 0.2s ease;
  }

  .handle:hover {
    color: #6b7280;
    background-color: #f3f4f6;
  }

  .indicator-text {
    flex: 1;
    font-size: 14px;
    color: #374151;
    font-weight: 500;
  }

  .indicator-index {
    margin-right: 12px;
    background-color: #3b82f6;
    color: white;
    border-radius: 50%;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: 600;
    flex-shrink: 0;
  }

  .remove-icon {
    cursor: pointer;
    color: #9ca3af;
    font-size: 18px;
    padding: 6px;
    border-radius: 50%;
    transition: all 0.3s ease;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
  }

  .remove-icon:hover {
    color: #ef4444;
    background-color: #fef2f2;
    transform: scale(1.1);
  }

  /* 限制提示样式 */
  .indicator-limit {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background-color: #fffbeb;
    border: 1px solid #fcd34d;
    border-radius: 8px;
    margin-top: 12px;
    font-size: 14px;
    color: #d97706;
    font-weight: 500;
  }

  .warning-icon {
    margin-right: 8px;
    font-size: 16px;
  }

  /* 空状态样式 */
  .indicator-empty {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 48px 24px;
    background-color: #f9fafb;
    border: 2px dashed #d1d5db;
    border-radius: 8px;
    color: #6b7280;
    font-size: 14px;
    font-weight: 500;
  }

  .info-icon {
    margin-right: 8px;
    font-size: 16px;
  }

  /* ===== 响应式设计 ===== */

  /* 平板设备 (768px以下) */
  @media (max-width: 768px) {
    .indicator-modal-overlay {
      padding: 16px;
    }

    .indicator-modal {
      max-height: 90vh;
      border-radius: 16px;
    }

    .indicator-modal-header {
      padding: 16px 20px;
    }

    .indicator-modal-header h3 {
      font-size: 16px;
    }

    .indicator-dialog {
      padding: 20px;
    }

    .checkbox-group {
      grid-template-columns: repeat(2, 1fr);
      gap: 10px;
    }

    .checkbox-item {
      padding: 10px 12px;
      min-height: 44px;
    }

    .tab {
      padding: 10px 12px;
      font-size: 13px;
    }
  }

  /* 手机设备 (480px以下) */
  @media (max-width: 480px) {
    .indicator-modal-overlay {
      padding: 12px;
      align-items: flex-end;
    }

    .indicator-modal {
      width: 100%;
      max-height: 85vh;
      border-radius: 20px 20px 0 0;
      margin-bottom: 0;
    }

    .indicator-modal-header {
      padding: 16px;
    }

    .indicator-modal-header h3 {
      font-size: 15px;
    }

    .indicator-dialog {
      padding: 16px;
    }

    .indicator-tabs {
      flex-wrap: wrap;
    }

    .tab {
      flex: 1 0 50%;
      border-right: none;
      border-bottom: 1px solid #e5e7eb;
    }

    .tab:nth-child(2n) {
      border-left: 1px solid #e5e7eb;
    }

    .tab:nth-last-child(-n+2) {
      border-bottom: none;
    }

    .checkbox-group {
      grid-template-columns: 1fr;
      gap: 8px;
    }

    .checkbox-item {
      padding: 12px;
      min-height: 48px;
    }

    .checkbox-label {
      font-size: 14px;
    }

    .indicator-modal-footer {
      padding: 16px;
      flex-direction: column;
      gap: 8px;
    }

    .indicator-modal-footer .btn {
      width: 100%;
      margin: 0;
    }

    .close-button {
      width: 28px;
      height: 28px;
      font-size: 20px;
    }
  }

  /* 超小屏幕设备 (360px以下) */
  @media (max-width: 360px) {
    .indicator-modal-overlay {
      padding: 8px;
    }

    .indicator-modal {
      max-height: 90vh;
    }

    .indicator-dialog {
      padding: 12px;
    }

    .tab {
      padding: 8px 10px;
      font-size: 12px;
    }

    .checkbox-item {
      padding: 10px;
      min-height: 44px;
    }

    .checkbox-label {
      font-size: 13px;
    }
  }
.filter-view {
  padding: 20px;
  padding-bottom: 100px; /* 为底部导航栏留出空间 */
  position: relative;
  background-color: #ffffff;
  height: 100vh;
  box-sizing: border-box;
  overflow: hidden;
}

/* 保存策略对话框样式 */
.save-strategy-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 确认对话框样式 */
.confirm-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.5);
}

.confirm-dialog {
  position: relative;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  width: 90%;
  max-width: 400px;
  z-index: 2001;
  overflow: hidden;
}

.confirm-message {
    font-size: 14px;
    line-height: 1.6;
    color: #333;
    margin: 0;
    text-align: center;
    padding: 10px 0;
  }

  /* 确认对话框响应式设计 - 平板设备 */
  @media (max-width: 768px) {
    .confirm-dialog {
      width: 95%;
      max-width: 95%;
    }

    .dialog-header h3 {
      font-size: 16px;
    }

    .confirm-message {
      font-size: 15px;
      line-height: 1.8;
    }

    .dialog-footer {
      flex-direction: column;
      gap: 10px;
    }

    .dialog-footer button {
      width: 100%;
      padding: 10px;
    }
  }

  /* 确认对话框响应式设计 - 手机设备 */
  @media (max-width: 480px) {
    .confirm-dialog-overlay {
      padding: 12px;
      align-items: flex-end;
    }

    .confirm-dialog {
      width: 100%;
      border-radius: 20px 20px 0 0;
      margin-bottom: 0;
    }

    .dialog-header {
      padding: 16px;
    }

    .dialog-header h3 {
      font-size: 15px;
    }

    .dialog-body {
      padding: 20px 16px;
    }

    .confirm-message {
      font-size: 14px;
    }

    .dialog-footer {
      padding: 16px;
    }
  }

  /* 确认对话框响应式设计 - 超小屏幕设备 */
  @media (max-width: 360px) {
    .confirm-dialog-overlay {
      padding: 8px;
    }

    .dialog-body {
      padding: 16px 12px;
    }

    .confirm-message {
      font-size: 13px;
    }
  }

.dialog-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}



.dialog-content {
  position: relative;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow: hidden;
  z-index: 2001;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e8e8e8;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #666;
}

.dialog-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.form-control {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.form-control:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.form-control::placeholder {
  color: #bfbfbf;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #e8e8e8;
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
}

/* 列选择器样式 */
.column-selector {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.selector-columns {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.selected-columns, .available-columns {
  flex: 1;
  background: white;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  max-height: 300px;
  overflow-y: auto;
}

.selected-columns h4, .available-columns h4 {
  margin: 0;
  padding: 10px 15px;
  background-color: #e9ecef;
  border-bottom: 1px solid #dee2e6;
  font-size: 14px;
  color: #495057;
  border-radius: 6px 6px 0 0;
}

.column-list {
  padding: 10px;
}

.column-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 10px;
  margin-bottom: 5px;
  background-color: #f8f9fa;
  border-radius: 4px;
  font-size: 13px;
}

.column-item button {
  padding: 4px 8px;
  margin-left: 5px;
}

/* 列选择器对话框响应式设计 */
@media (max-width: 768px) {
  .column-selector-dialog .dialog-content {
    width: 95%;
    max-width: 95%;
    height: 80vh;
  }

  .selector-columns {
    flex-direction: column;
    gap: 15px;
  }

  .selected-columns, .available-columns {
    max-height: 200px;
  }

  .column-item {
    padding: 10px;
    font-size: 14px;
  }

  .column-item button {
    padding: 6px 12px;
    font-size: 14px;
  }

  .dialog-header h3 {
    font-size: 16px;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 10px;
  }

  .dialog-footer button {
    width: 100%;
    padding: 10px;
  }
}

/* PC端优化 */
@media (min-width: 769px) {
  .column-selector-dialog .dialog-content {
    width: 70%;
    max-width: 800px;
  }
}

.column-item button {
  padding: 4px 8px;
  margin-left: 5px;
  font-size: 11px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.column-item button:hover {
  background-color: #40a9ff;
}

.column-item button:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.column-actions {
  display: flex;
  gap: 5px;
}

/* 选择展示按钮样式 */
.select-columns-btn {
  width: 100%;
  padding: 10px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.select-columns-btn:hover {
  background-color: #40a9ff;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.btn-secondary {
  background: #f5f5f5;
  color: #333;
  border-color: #d9d9d9;
}

.btn-secondary:hover {
  background: #e6e6e6;
  border-color: #bfbfbf;
}

.btn-primary {
  background: #1890ff;
  color: white;
}

.btn-primary:hover {
  background: #40a9ff;
  border-color: #40a9ff;
}

/* 顶部标题栏 */
.header {
  margin-bottom: 20px;
}

.title-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 10px;
  border-bottom: 1px solid #e8e8e8;
}

.title-button {
  font-size: 14px;
  color: #666;
  padding: 6px 12px;
  background: #f0f0f0;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-weight: 500;
}

.title-button:hover {
  background: #e6f7ff;
  border-color: #40a9ff;
  color: #1890ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.2);
}

.title-button:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(24, 144, 255, 0.3);
}

.title-bar h1 {
  color: #333;
  font-size: 20px;
  margin: 0;
}

.filter-link {
  color: #1890ff;
  text-decoration: underline;
  cursor: pointer;
  font-size: 14px;
  padding: 4px;
  display: inline-block;
}

.filter-link:hover {
  color: #40a9ff;
  text-decoration: none;
}

/* 主内容区域 */
.content {
  display: flex;
  height: calc(100vh - 150px);
  gap: 20px;
}

/* 表格容器 */
.table-container {
  flex: 1;
  border: none;
  border-radius: 4px;
  overflow: hidden;
  background: white;
  display: flex;
  flex-direction: column;
}

/* 表格头部 */
.table-header {
  display: flex;
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  position: sticky;
  top: 0;
  z-index: 10;
}

.header-cell {
  padding: 12px 8px;
  text-align: center;
  font-size: 14px;
  font-weight: bold;
  color: #333;
  flex: 1;
  min-width: 80px;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.header-cell.blue-text {
  color: #1890ff;
}

.header-cell:hover {
  background-color: #f0f0f0;
}

.header-cell.sortable {
  cursor: pointer;
}

.time-range {
  font-size: 12px;
  color: #999;
  font-weight: normal;
  margin-top: 2px;
}

.sort-icon {
  font-size: 10px;
  color: #1890ff;
  margin-top: 2px;
}

/* 指标徽章 */
.indicator-badge {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: white;
  font-weight: bold;
}

.indicator-1 {
  background: #ff4d4f;
}

.indicator-2 {
  background: #faad14;
}

.indicator-3 {
  background: #1890ff;
}

/* 表格内容 */
.table-body {
  overflow-y: auto;
  height: calc(100% - 50px);
  background-color: #fafafa;
}

/* 行样式 - 添加清晰分隔和背景色区分 */
.table-row {
  display: flex;
  background-color: #ffffff;
  margin-bottom: 2px;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
  transition: all 0.2s ease;
}

.table-row:hover {
  background: #f5f5f5;
}

.average-row {
  background: #fff7e6;
  font-weight: bold;
}

.summary-toggle {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.summary-toggle:hover {
  color: #1890ff;
}

.toggle-icon {
  font-size: 10px;
  color: #999;
  transition: transform 0.2s;
}

.summary-toggle:hover .toggle-icon {
  color: #1890ff;
}

.table-cell {
  padding: 10px 5px;
  text-align: center;
  font-size: 14px;
  color: #333;
  flex: 1;
  min-width: 80px;
  border-right: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-family: 'Arial', sans-serif;
}

/* 突出显示重要数据 */
.table-cell:not(:first-child) {
  font-weight: 500;
}

/* 表格行悬停效果增强 */
.table-row:hover {
  background-color: #f6f6f6;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 数值变化颜色 */
.table-cell.positive {
  color: #f5222d;
}

.table-cell.negative {
  color: #52c41a;
}

/* 第一列股票信息样式增强 */
.table-cell:first-child {
  border-left: none;
  align-items: flex-start;
  justify-content: center;
  padding-left: 10px;
}

/* 股票名称和代码 */
.stock-name {
  font-weight: bold;
  color: #333;
  margin-bottom: 2px;
  /* 添加省略号显示 */
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: help;
}

.stock-code {
  font-size: 12px;
  color: #999;
  /* 添加省略号显示 */
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: help;
}

/* 自定义悬浮提示样式 */
.custom-tooltip {
  position: fixed;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  z-index: 2000;
  pointer-events: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

/* 右侧说明面板 */
.info-panel {
  width: 250px;
  flex-shrink: 0;
}

.info-content {
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 16px;
  height: fit-content;
}

.info-content h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e8e8e8;
}

.info-text {
  font-size: 13px;
  color: #666;
  line-height: 1.6;
}

.info-text p {
  margin-bottom: 8px;
  text-align: justify;
}

.info-text p:last-child {
  margin-bottom: 0;
}

/* 悬浮按钮 */
.floating-button {
  position: fixed;
  left: 30px;
  top: 50%;
  transform: translateY(-50%);
  width: 40px;
  height: 40px;
  background: #ff4d4f;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(255, 77, 79, 0.4);
  z-index: 100;
}

/* 筛选面板样式 */
.filter-panel {
  position: fixed;
  top: 0;
  right: 0;
  width: 100%;
  height: 100vh;
  z-index: 1000;
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  overflow: hidden;
}

/* 筛选面板覆盖层 */
.filter-panel-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}

/* 筛选面板顶部标题样式 */
.filter-panel-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

/* 筛选面板标题区域样式 */
.filter-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
}

/* 筛选标题样式 */
.filter-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
  flex: 1;
  text-align: center;
}

/* 保存策略链接样式 */
.save-strategy {
  color: #1890ff;
  text-decoration: none;
  font-size: 14px;
  cursor: pointer;
}

.save-strategy:hover {
  color: #40a9ff;
  text-decoration: underline;
}



.filter-panel-content {
  background: #fff;
  width: 100%;
  max-width: 500px;
  height: 100vh;
  overflow-y: auto;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
  transform: translateX(100%);
  animation: slideIn 0.3s ease-out forwards;
  /* 使用flex布局确保底部按钮固定在底部 */
  display: flex;
  flex-direction: column;
  padding-bottom: 0;
  /* 确保内容区域正确计算高度 */
  position: relative;
}

@keyframes slideIn {
  to {
    transform: translateX(0);
  }
}

.filter-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e8e8e8;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 1001;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 重置按钮样式 */
.reset-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
  color: #666;
}

.reset-btn:hover {
  background: #f5f5f5;
  color: #1890ff;
  transform: rotate(90deg);
}

.reset-btn:active {
  transform: rotate(180deg);
}

.filter-panel-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
  font-weight: 500;
}

.save-strategy-btn {
  font-size: 14px;
  color: #1890ff;
  cursor: pointer;
  text-decoration: none;
  padding: 6px 12px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.save-strategy-btn:hover {
  background: #e6f7ff;
  color: #40a9ff;
}

/* 策略选择样式 */
.strategy-selection {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  flex-wrap: wrap;
}

.strategy-label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  margin-right: 8px;
  flex-shrink: 0;
}

/* 策略筛选标签样式 */
.strategy-filter-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  width: 100%;
  flex-wrap: wrap;
}

.filter-tab {
  padding: 6px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 16px;
  background: #fff;
  color: #666;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.filter-tab:hover {
  border-color: #1890ff;
  color: #1890ff;
  background: #e6f7ff;
}

.filter-tab.active {
  background: #1890ff;
  color: #fff;
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

.strategy-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.strategy-tag {
      padding: 8px 16px;
      border: 2px solid #d9d9d9;
      border-radius: 20px;
      font-size: 14px;
      color: #333;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s ease;
      min-width: 80px;
      text-align: center;
      background-color: #fff;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

/* 不同策略的颜色标识 */
.strategy-tracking {
  background: #ff4d4f;
  border-color: #ff4d4f;
}

.strategy-excellent {
  background: #faad14;
  border-color: #faad14;
}

.strategy-rc {
  background: #1890ff;
  border-color: #1890ff;
}

.strategy-efficiency {
  background: #52c41a;
  border-color: #52c41a;
}

.strategy-tag:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      border-color: #40a9ff;
    }

    .strategy-tag:active {
      transform: translateY(0);
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
      opacity: 0.8;
      scale: 0.98;
    }

    .strategy-tag.selected {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  background-color: #e6f7ff;
  transform: translateY(-1px);
}

/* 策略徽章样式 */
.strategy-badge {
  margin-left: 4px;
  font-size: 12px;
  vertical-align: middle;
}

/* 指标策略样式 */
.indicator-strategy {
  border-left: 3px solid #52c41a;
}

/* 筛选策略样式 */
.filter-strategy {
  border-left: 3px solid #faad14;
}

/* 市场选择样式 */
.market-selection {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  flex-wrap: wrap;
}

/* 地区标签样式 */
.market-label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  margin-right: 8px;
}

/* 国旗图标样式 */
.flag-icon {
  margin-right: 6px;
  display: inline-block;
  vertical-align: middle;
}

.market-tag {
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 20px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fff;
}

.market-tag:hover {
  border-color: #1890ff;
  color: #1890ff;
  background: #e6f7ff;
}

.market-tag.active {
  background: #1890ff;
  color: #fff;
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

/* 筛选表单样式 */
.filter-form {
  padding: 20px;
  /* 为底部按钮留出足够空间，防止输入框被遮挡 */
  padding-bottom: 0;
}

.filter-item {
  margin-bottom: 20px;
}

.filter-item:last-child {
  margin-bottom: 0;
}

.filter-item label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.input-group input {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
  transition: all 0.3s ease;
  background: #fff;
}

.input-group input::placeholder {
  color: #999;
}

.input-group input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.input-group span {
  color: #999;
  font-size: 14px;
  padding: 0 4px;
  white-space: nowrap;
}

/* 错误提示样式 */
.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 6px;
  line-height: 1.4;
}

/* 筛选面板底部样式 - 修复定位问题 */
.filter-panel-footer {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
  /* 使用relative定位确保与内容区域一起滚动 */
  position: relative;
  width: 100%;
  box-sizing: border-box;
  /* 适配筛选面板宽度 */
  max-width: 100%;
  margin-top: 20px;
}

.selected-btn, .result-btn {
  padding: 12px 28px;
  border: none;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  outline: none;
  min-width: 130px;
  text-align: center;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
}

.selected-btn {
  background: #f8f9fa;
  color: #495057;
  border: 1px solid #e9ecef;
}

.selected-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
  background: #e6f7ff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
  transform: translateY(-2px);
}

.selected-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.result-btn {
  background: linear-gradient(135deg, #1890ff, #40a9ff);
  color: #fff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.result-btn:hover {
  background: linear-gradient(135deg, #40a9ff, #65b4f0);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.4);
  transform: translateY(-2px);
}

.result-btn:active {
  transform: translateY(0);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

/* 预览模式提示信息样式 */
.preview-mode-message {
  width: 100%;
  padding: 40px 20px;
  text-align: center;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin: 20px 0;
  border: 1px dashed #dee2e6;
}

.preview-message-content {
  display: inline-flex;
  align-items: center;
  gap: 15px;
}

.preview-icon {
  font-size: 32px;
}

.preview-text {
  text-align: left;
}

.preview-title {
  font-size: 18px;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 5px;
}

.preview-description {
  font-size: 14px;
  color: #6c757d;
}

/* 分页控件样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  padding-bottom: 80px; /* 增加底部内边距，避免被底部导航栏遮挡 */
  background: #fafafa;
  border-top: 1px solid #e8e8e8;
}

.pagination-info {
  font-size: 14px;
  color: #666;
}

.pagination-info select {
  margin: 0 8px;
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  background: white;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-controls button {
  padding: 4px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  color: #333;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.pagination-controls button:hover:not(:disabled) {
  color: #1890ff;
  border-color: #1890ff;
}

.pagination-controls button:disabled {
  color: #bfbfbf;
  border-color: #d9d9d9;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: #666;
  min-width: 100px;
  text-align: center;
}  /* 响应式设计 - 平板设备 */
  @media (max-width: 768px) {
    /* 调整顶部标题栏 */
    .header {
      height: auto;
      padding: 10px 15px;
    }

    /* 调整筛选面板宽度和标题样式 */
    .filter-panel {
      width: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
    }



    .filter-panel-header {
      padding: 12px 15px;
      border-bottom: 1px solid #eee;
    }

    .filter-title {
      font-size: 18px;
      color: #333;
    }

    /* 移动端筛选面板适配 */
    .filter-panel-content {
      max-width: 100%;
      width: 100%;
      height: 100vh;
      background-color: white;
      border-radius: 0;
      box-shadow: none;
      padding-bottom: 0;
    }



    /* 市场选择标签适配 */
    .market-selection {
      justify-content: center;
      flex-wrap: wrap;
      gap: 10px;
      padding: 15px;
      background-color: #f5f7fa;
      margin-bottom: 10px;
    }

    .market-label {
      width: 100%;
      text-align: left;
      font-weight: bold;
      margin-bottom: 5px;
    }

    .market-tag {
      padding: 8px 16px;
      font-size: 14px;
      margin-bottom: 0;
      border-radius: 20px;
      transition: all 0.3s ease;
    }

    /* 筛选表单适配 - 修复输入框被遮挡问题 */
    .filter-form {
      padding: 15px;
      display: flex;
      flex-direction: column;
      gap: 16px;
      /* 为底部固定按钮留出足够空间 */
      padding-bottom: 0;
    }

    .filter-item {
      margin-bottom: 0;
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    .filter-item label {
      font-weight: 500;
      color: #333;
      font-size: 14px;
    }

    .input-group {
      flex-wrap: wrap;
      gap: 10px;
    }

    .input-group input {
      padding: 10px 12px;
      font-size: 14px;
      min-height: 48px;
      border: 1px solid #ddd;
      border-radius: 8px;
      transition: border-color 0.3s;
    }

    .input-group input:focus {
      outline: none;
      border-color: #4a90e2;
    }

    /* 底部按钮适配 - 确保始终固定在底部 */
    .filter-panel-footer {
      display: flex;
      justify-content: space-between;
      padding: 15px 15px 20px;
      margin-top: 10px;
      border-top: 1px solid #eee;
      /* 使用relative定位确保与内容区域一起滚动 */
      position: relative;
      width: 100%;
      box-sizing: border-box;
      max-width: 100%;
    }

    .selected-btn, .result-btn {
      padding: 14px 30px;
      font-size: 16px;
      min-width: 140px;
      min-height: 50px;
      border-radius: 10px;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
      position: relative;
      overflow: hidden;
    }

    .selected-btn {
      background: #f8f9fa;
      color: #495057;
      border: 1px solid #e9ecef;
    }

    .selected-btn:hover {
      border-color: #1890ff;
      color: #1890ff;
      background: #e6f7ff;
      box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
      transform: translateY(-2px);
    }

    .selected-btn:active {
      transform: translateY(0);
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }

    .result-btn {
      background: linear-gradient(135deg, #1890ff, #40a9ff);
      color: white;
      border: none;
      font-weight: 500;
      box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
    }

    .result-btn:hover {
      background: linear-gradient(135deg, #40a9ff, #65b4f0);
      box-shadow: 0 6px 16px rgba(24, 144, 255, 0.4);
      transform: translateY(-2px);
    }

    .result-btn:active {
      transform: translateY(0);
      box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
    }

    /* 保存策略按钮适配 */
    .save-strategy {
      font-size: 13px;
      color: #4a90e2;
      text-decoration: none;
    }

    .title-bar {
      gap: 10px;
    }

    .title-icon {
      font-size: 14px;
    }

    h1 {
      font-size: 18px;
    }

    .filter-link {
      font-size: 12px;
    }

    /* 主内容区域 */
    .content {
      flex-direction: column;
      gap: 15px;
      padding: 10px;
    }

    /* 表格容器 */
    .table-container {
      overflow-x: auto;
      -webkit-overflow-scrolling: touch;
    }
  }

  /* 表格头部 */
  .table-header {
    font-size: 12px;
  }

  .header-cell {
    min-width: 80px;
    padding: 10px 5px;
  }

  .time-range {
    font-size: 10px;
  }

  /* 表格内容 */
  .table-row {
    font-size: 13px;
  }

  .table-cell {
    min-width: 80px;
    padding: 10px 5px;
  }

  /* 右侧说明面板 */
  .info-panel {
    width: 100%;
    order: 2;
  }

  .info-content {
    padding: 12px;
  }

  .info-content h3 {
    font-size: 14px;
  }

  .info-text {
    font-size: 12px;
  }

  /* 悬浮按钮 */
  .floating-button {
    width: 35px;
    height: 35px;
    font-size: 14px;
    left: 15px;
  }

  /* 分页控件 */
  .pagination {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    padding-bottom: 80px; /* 增加底部内边距，避免被底部导航栏遮挡 */
    background: #fafafa;
    border-top: 1px solid #e8e8e8;
  }

  .pagination-info {
    font-size: 14px;
    color: #666;
  }

  .pagination-controls {
    gap: 5px;
  }

  .pagination-controls button {
    padding: 3px 8px;
    font-size: 12px;
    min-width: 28px;
  }

  .page-info {
    font-size: 12px;
    min-width: 80px;
  }

  /* 响应式设计 - 手机设备 */
  @media (max-width: 480px) {
    /* 表格单元格进一步缩小 */
    .header-cell,
    .table-cell {
      min-width: 50px;
      padding: 6px 2px;
      font-size: 11px;
    }



    /* 表头文本适配 */
    .header-cell span {
      font-size: 10px;
    }

    /* 股票名称和代码 */
    .stock-name {
      font-size: 12px;
      line-height: 1.2;
    }

    .stock-code {
      font-size: 10px;
      line-height: 1.2;
    }

    /* 简化分页控件 */
    .pagination {
      flex-direction: column;
      gap: 8px;
      padding: 10px;
    }

    .pagination-controls {
      justify-content: center;
      flex-wrap: wrap;
    }

    .pagination-controls button {
      padding: 4px 8px;
      font-size: 11px;
      min-width: 24px;
      min-height: 32px;
    }

    .page-info {
      font-size: 11px;
      min-width: 60px;
    }

    /* 筛选面板优化 */
    .filter-panel {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.7);
      z-index: 1000;
      display: flex;
      align-items: flex-end;
      justify-content: center;
      padding-bottom: 0;
    }

    .filter-panel-content {
      width: 100%;
      max-width: 100%;
      height: 66.67vh; /* 只覆盖屏幕的三分之二 */
      overflow-y: auto;
      -webkit-overflow-scrolling: touch;
      background-color: white;
      border-radius: 20px 20px 0 0; /* 添加圆角 */
      box-shadow: 0 -2px 20px rgba(0, 0, 0, 0.2);
      padding-bottom: 0;
    }



    /* 输入框调整 */
    .input-group {
      flex-direction: column;
      align-items: stretch;
      gap: 10px;
    }

    .input-group span {
      align-self: center;
      margin: 4px 0;
      font-size: 13px;
    }

    .input-group input {
      padding: 12px 14px;
      font-size: 14px;
      min-height: 50px;
      border-radius: 10px;
    }

    /* 底部按钮组适配 */
    .filter-panel-footer {
      flex-direction: column;
      gap: 15px;
      padding: 20px;
      border-top: 1px solid #eee;
      background: #ffffff;
      box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.08);
      position: relative;
      width: 100%;
      box-sizing: border-box;
    }

    .selected-btn, .result-btn {
      width: 100%;
      margin: 0;
      padding: 18px 24px;
      font-size: 17px;
      min-height: 60px;
      border-radius: 14px;
      font-weight: 500;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      position: relative;
      overflow: hidden;
    }

    .selected-btn {
      background: #f8f9fa;
      color: #495057;
      border: 1px solid #e9ecef;
    }

    .selected-btn:hover {
      border-color: #1890ff;
      color: #1890ff;
      background: #e6f7ff;
      box-shadow: 0 6px 16px rgba(24, 144, 255, 0.2);
      transform: translateY(-2px);
    }

    .selected-btn:active {
      transform: translateY(0);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .result-btn {
      background: linear-gradient(135deg, #1890ff, #40a9ff);
      color: white;
      border: none;
      box-shadow: 0 6px 16px rgba(24, 144, 255, 0.3);
    }

    .result-btn:hover {
      background: linear-gradient(135deg, #40a9ff, #65b4f0);
      box-shadow: 0 8px 20px rgba(24, 144, 255, 0.4);
      transform: translateY(-2px);
    }

    .result-btn:active {
      transform: translateY(0);
      box-shadow: 0 6px 16px rgba(24, 144, 255, 0.3);
    }

    /* 优化标题栏 */
    .title-bar {
      justify-content: space-between;
      padding: 8px 10px;
    }

    h1 {
      font-size: 16px;
    }

    /* 表格内容区域滚动优化 */
    .table-body {
      overflow-x: auto;
    }

    /* 总结行优化 */
    .average-row .table-cell {
      font-size: 10px;
      padding: 8px 2px;
    }

    /* 市场选择标签优化 */
    .market-selection {
      padding: 12px 15px;
      gap: 8px;
    }

    .market-tag {
      padding: 6px 12px;
      font-size: 13px;
      border-radius: 16px;
    }

    /* 筛选表单优化 */
    .filter-form {
      gap: 14px;
    }

    .filter-item {
      gap: 6px;
    }

    .filter-item label {
      font-size: 13px;
    }
  }

</style>
